0
\$\begingroup\$

Here is the code I have written for an AI:

public Transform player;
public NavMeshAgent Enemy;
public CharacterPowers CharPow;
public GameObject me;


// Update is called once per frame
void Update () {
    Vector3 targetDir = player.position - transform.position;
    float angleToPlayer = (Vector3.Angle(targetDir, transform.forward));

    if (angleToPlayer >= -90 && angleToPlayer <= 90)
    {
        RaycastHit hit;
        Physics.Raycast(me.transform.position, player.position, out hit);

        if(hit.transform.tag == "MainChar")
        {


            if(CharPow.IsCloaked == false)
            {
                Debug.Log("Player in sight!");
                Enemy.destination = player.position;
            }

        }


    }


}

However, according to the error message, the line

if(hit.transform.tag == "MainChar")

is missing a reference to an object. I have checked, and yes, the player character does have the tag. Everything else used to work, such as the cloaking mechanic. However, now nothing about the AI works at all.

\$\endgroup\$
1
\$\begingroup\$

Raycasting methods take a start point and a direction, but you're passing two points: a start and an end. The second point will not be interpreted the way you expect.

Instead, your second argument should be:

player.position - me.transform.position

to get a vector pointing toward the player from the start point at "me".

You should still check whether you've hit anything at all before you try to access the members of the resulting RaycastHit, so you don't hit NullReferenceExceptions even when unusual situations arise (like me being inside the player's collider)

You'll also want to use the CompareTag method instead of .tag == for efficiency.

\$\endgroup\$
  • \$\begingroup\$ Note: To check whether the raycast hit something, Physics.Raycast returns a bool, so just use if (Physics.Raycast...) {...} where the rest of your code is inside the body of the if \$\endgroup\$ – Ed Marty Jul 4 '18 at 13:52
0
\$\begingroup\$

I think that instead of if(hit.transform.tag == "MainChar") you should use if(hit.gameObject.tag == "MacinChar"). Did you try this?

\$\endgroup\$
  • \$\begingroup\$ Yes. It does not work. \$\endgroup\$ – Spaceguy99 Jul 3 '18 at 23:33
  • \$\begingroup\$ Try to put some Debug.Log(hit.transform.tag); after Physics.Raycast(...) and see what tag you'll get \$\endgroup\$ – Seweryn Pokutycki Jul 3 '18 at 23:35
  • \$\begingroup\$ it returns the same error request as usual \$\endgroup\$ – Spaceguy99 Jul 3 '18 at 23:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.