- Home /
Assign gameObject to a variable at runtime
I am trying to set the variable "Player" to the GameObject that is being controlled by the user in a script attached to an enemy, via:
var Player : GameObject
The problem arises when I use the Inspector to set the variable. In a prefab, I cannot set the specific game object as this variable, and my enemy just wanders aimlessly. Is there a way to set this variable at runtime?
Answer by hijinxbassist · May 23, 2012 at 05:45 PM
Sure, you can set it in Awake() or Start(). If this var is not on the players script, you will have to find a hard path or assign it using one of the Find methods. ex
Player=GameObject.FindGameObjectWithTag("Player");
If this is on the player, you could say
Player=this.gameObject;
Thanks! I was not aware the Find function existed, this is exactly what I was looking for.
Answer by junedmmn · Mar 15, 2019 at 05:02 PM
Use Player = GameObject.Find("stringName");
or Player = GameObject.FindGameObjectWithTag("stringName");
note that both the methods work only if GameObject is Active in the hierarchy.
Your answer
Follow this Question
Related Questions
How to use unityeditor and where I need it? 1 Answer
Acessing scripts in other game objects with prefabs, without using GameObject.Find 1 Answer
how could i make the enemy follow me and stop with the distance to me 1 Answer
Horror Game AI script recommendation? 1 Answer
Ai Upgrade?? Possible 1 Answer