- Home /
Script finds a non-existing object
I have a really weird problem with my game. I'm using GameObject.FindWithTag in the Update() to find the player transform for my camera script. This is obviously very basic stuff. But now, for some reason, the script finds an object called Player(clone), that doesn't exist in the current scene. Every other script and object in the scene works fine. If I manually drag the player in inspector view, it works fine. If I double click the transform variable in the script that currently is Player(clone), it shows an animator controller in the inspector view and no other components. It just doesn't make any sense. The name Player(clone) would indicate that it would be an object created using Instantiate, but I haven't used it at all. I have no idea how to fix this.
Also, I can't believe that "wtf" was an actual approved suggested tag.
Using gameObject.Find... in Update is one of the biggest sins of a unity developer. Consider storing the reference somewhere (i.e. drag into inspactor. or reference through Singleton(i.e. player.instance.gameobject). It will not answer to your question but will fix your problem.
found this myself , what i did was look for a specific script on the gameobject then using findObjectOftype().transform if you want the transform or findObjectOftype().gameobject for the gameobject not exact code so look up the proper references but those should work seems to be a bug in unity 5.
Answer by brunopava · Apr 28, 2015 at 12:02 PM
Personaly, I like to make a Singleton and cache some importante variables in it like player, points, list of enemies and etc. The upside is that you make sure that there will be only one instance of the Singleton in your scene, therefore you will not have this problem of accessing other instances instead of the one you want.
The code for a Singleton is:
using UnityEngine;
using System.Collections;
public class SingletonExample : MonoBehaviour
{
private static SingletonExample _instance;
public static SingletonExample instance
{
get{
if(_instance == null)
{
GameObject singletonHolder = new GameObject("[SingletonExample]");
_instance= singletonHolder.AddComponent<SingletonExample>();
}
return _instance;
}
}
public void Awake()
{
//ONLY IF YOU WANT IT TO NOT EVER BE DESTROYED
DontDestroyOnLoad(gameObject);
}
}
And you call like this:
SingletonExample.instance.someVariableYouCreated.ActionYouWantItToTake();
Or in your case:
SingletonExample.instance.player instead of GameObject.FindWithTag("Player");
Dont forget to declare your variables and assign them onto the Singleton.
If you want to learn more about check this link: http://en.wikipedia.org/wiki/Singleton_pattern
Your answer

Follow this Question
Related Questions
Array of prefabs 0 Answers
Cast Source Instantiating Error 1 Answer
How to control variable of prefab and its clone 0 Answers
How to change sprite on a cloned object? 1 Answer
Unity 2D : How to make a perfect clone of my Game Object? 3 Answers