简体   繁体   中英

Unity 5. Raycast compare tag

I am using a raycast system to detect items in the world, and if the raycast detects an apple and I press "E" my character should pick up that specific apple. Same goes with any other objects that would be pickable.

I can't figure out a way of doing this neatly besides hard coding every single item with an "IF" statement to check if that specific item was targeted.

I have my thought on Comparing Tags but I don't see how I wouldn't have to hard code everything nontheless.

void Fire()
{
    if (Physics.Raycast(transform.position, transform.forward, out hit, rayRange))
    {
        // If (Raycast hit enemy) Damage Enemy Accordingly based on weapon damage. 
        // If (Raycast hit Apple) Pick up apple.
        // If (Raycast hit Drink) Pick up drink. 

        Destroy(hit.transform.gameObject); // Debug Only
        Debug.Log(hit.transform.name); // Debug Only
    }

    nextFire = Time.time + fireRate; // Don't mind this.
}

I think you're looking for the function: GameObject.SendMessage

if (Physics.Raycast(transform.position, transform.forward, out hit, rayRange))
{
    hit.collider.SendMessage("CheckHit");

   // Destroy(hit.transform.gameObject); // Debug Only
   // Debug.Log(hit.transform.name); // Debug Only
}

Then in your script for "enemy","Apple" or "Drink" put a function called "CheckHit"

ie

public class AppleController : MonoBehaviour
{
    public void CheckHit();
}

If you want to add variables to "CheckHit()" then call

hit.collider.SendMessage("CheckHit", 1.0f);

public class AppleController : MonoBehaviour
{
    public void CheckHit(float something);
}

https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html

My previous answer works if you want to call a function within the hit.transform class.

I thought if you wanted to call a function from within the current Class that the following way is better.

If you wanted to call a function from the fire() function you could always do what is explained in:

Calling a function from a string in C#

just name your functions such as

public void HandleApple();
public void HandleEnemy();

get the function to call with the name using the "hit" tag

There are a few ways to call a function by name described in the above link, but I think by using the "hit.transform.tag" all you would have to do is name your function related to it's tag

if (Physics.Raycast(transform.position, transform.forward, out hit, rayRange))
string functionName = "Handle" + hit.transform.tag; // tag is "Apple"

Then invoke the function by calling the function by "functionName" ("HandleApple")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM