How to convert GameObject variable to string in c#?

hello i’ve just started using unity and programming but im having a problem when i use the GameObject variable in a “string” it keeps on giving me this error message: cannot convert ‘UnityEngine.GameObject’ to ‘string’ heres the code i used:

{

public GameObject Enemy;

// Start is called before the first frame update
void Start()
{
   
}

// Update is called once per frame
private void OnTriggerEnter (Collider collision)
{
    if(collision.tag == "Player")
    {
        GameObject.Find(Enemy).GetComponent<UnityEngine.AI.NavMeshAgent>().enabled=true;
        GameObject.Find(Enemy).GetComponent<EnemyController>().enabled=true;
        GameObject.Find(Enemy).GetComponent<Animator>().enabled=true;
    }
}

}

GameObject.Find() takes a string parameter. You are giving it a GameObject. You can not do that.

If you are setting Enemy in the inspector, you don’t need GameObject.Find because you already have the game object. You can just work with it directly

private void OnTriggerEnter (Collider collision)
{
    if(collision.tag == "Player")
    {
        Enemy.GetComponent<UnityEngine.AI.NavMeshAgent>().enabled=true;
        Enemy.GetComponent<EnemyController>().enabled=true;
        Enemy.GetComponent<Animator>().enabled=true;
    }
}
1 Like

OMG THANK YOU I HAVE BEEN TRYING TO FIND ANSWER FOR LIKE 2 DAYS. i havent tryed it out yet but ill do it now

It’s important to note that if the Enemy object is not set, you will get a null reference exception. Also, if any of the 3 components you are accessing do not exist on that game object, you will also get a null reference exception

1 Like

ye i know. the reason im asking this question is bc this is a player detection for the NavMeshAgent and i didnt want to make 100’s of scripts for each enemy one by one and instead ill use the same script and then choosing what the enemy is

tank so much it worked!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms