- Home /
check if an instantiated opject is null
So it is a long story about what my program is supposed to in the end. But what i am having problems with is that i cant seem to get Gameobject.Find()
working right.
I am instantiating a gameobject, renaming it and changing some variables in a list which is on the instantiated object. But i do not want to create another one if there is already on present with the same name.
To avoid confusion, i am using an inputfield to get my variables inputName, inputShoots and inputHits
When i input my text and press the button it creates a gameobject even though one with the same name already is present
here is the code:
public void OnSumit()
{
if(GameObject.Find(inputName.text) == null)
{
shooter.GetComponent<ShooterScript>().hits.Clear();
shooter.GetComponent<ShooterScript>().shoots.Clear();
shooter.GetComponent<ShooterScript>().hits.Add(int.Parse(inputHits.text));
shooter.GetComponent<ShooterScript>().shoots.Add(int.Parse(inputShots.text));
shooter.name = inputName.text;
Instantiate(shooter);
}
}
Answer by KittenSnipes · Jan 26, 2018 at 11:04 AM
I like using lists because you can always reference back to them so I made a script using one. Hopefully it helps. Cheers!
//This is a list of objects to reference later
//Currently holds nothing
List<string> objects;
private void Start()
{
//Create a the list so it exists and is accessible
objects = new List<string>();
}
public void OnSubmit()
{
//If our list contains the objects name
if (objects.Contains(inputName))
{
//Tell us it contains it and return because it already exists
Debug.Log("ERROR: Object Already Exists!");
return;
}
//Else
else
{
//Do all of the component stuff
shooter.GetComponent<ShooterScript>().hits.Clear();
shooter.GetComponent<ShooterScript>().shoots.Clear();
shooter.GetComponent<ShooterScript>().hits.Add(int.Parse(inputHits.text));
shooter.GetComponent<ShooterScript>().shoots.Add(int.Parse(inputShots.text));
//This is most important
shooter.name = inputName.text;
Instantiate(shooter);
//The shooter.name is used to find if the object exists later on
objects.Add(shooter.name);
}
}
Worked perfectly. Good easy and quick solution. Thanks a lot <3