Unity won't Instantiate() outside of Start(), even though code is the same

I am trying to add a gameobject to my game using a socket connection. I have a SocketHandler class, which simply connects to my NodeJS socket server, which can also call a method on another class, which will add a new gameobject to the game. Here is how it basically works:

void Start () {
GameObject car = Instantiate(CarGameObject);
car.transform.parent = this.transform;
car.GetComponent<TestCar>().text.text = "Volkswagen";
}


This works fine and it adds the gameobject to the game upon starting. However, if I do something like this in my SocketHandler, it doesn't work:

var addCar = new AddCar();
string str = data.ToString();
Car data2 = JsonConvert.DeserializeObject<Car>(str);
});


and then inside my AddCar class, I have the AddNewCar() method:

public void AddNewCar(Car input) {
GameObject car = Instantiate(CarGameObject);
car.transform.parent = this.transform;
car.GetComponent<TestCar>().text.text = input.name;
}


it does not work. If I do a Debug.Log(input.name) inside the AddNewCar() method, it does log the name the server sends. It should do the exact same thing, but the AddNewCar() doesn't get added to the game. It simply does nothing.

What could be wrong?

• How are you calling AddCar? – user106170 Nov 2 '17 at 14:59
• @AytAyt addCar.AddNewCar(data2); – MortenMoulder Nov 3 '17 at 12:59
• Ok, my question is more, where did you put that line, and how do you call it. What is the script attached to? – user106170 Nov 3 '17 at 14:32
• Yeah, you aren't ever actually calling addCar as far as i can tell, which in turn means you aren't calling the AddNewCar method. Start is called automatically by Unity. You need to create something like: if (player input) is at (addCar button) then call AddNewCar. Or a timer or something. – user106170 Nov 12 '17 at 17:44