- Home /
Unity GetComponent
I am having a weird issue with unity
When I reopen the scene the code finds my player object but not the script component I fix this by removing the Player Object and just dragging a new player object to the scene. But if I close the scene and reopen the scene again I have to redo the process again.
The code below is not attach to the player object, it is attached to multiple object as this is how I locate the player on the scene for instantiated objects
void Start() {
//DontDestroyOnLoad(transform.gameObject);
player = GameObject.FindGameObjectWithTag("Player");
if (player == null)
{
Debug.Log("PLAYER NOT FOUND");
}
else {
Debug.Log("PLAYER FOUND");
}
ps = player.gameObject.GetComponent<PlayerStat>();
if (ps == null)
{
Debug.Log("PS NOT FOUND");
}
}
I'm not sure if this is the only problem, but isn't player already a GameObject? If that's the case, you should use: ps = player.GetComponent<PlayerStat>();
not ps = player.gameObject.GetComponent<PlayerStat>();
Also, I'm pretty sure the current syntax should be GameObject.FindWithTag("Player");
Check if there are more than one object with tag "Player".One of the ways are to find the game object(player) with the help of a unique player's name. This may help you . Nsks
Answer by LeonNoel · Dec 23, 2015 at 04:24 PM
After some epic and extreme debugging process(printing the values xD). @sandeepsmartest was correct there were 2 game objects with tag player. Zefans suggestion to remove gameObject also works. There is nothing wrong with the syntax on the version I am using.
Thanks :D