1
\$\begingroup\$

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();
socketio.On("addCar", (data) => {
    string str = data.ToString();
    Car data2 = JsonConvert.DeserializeObject<Car>(str);
    addCar.AddNewCar(data2);
});

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?

\$\endgroup\$
  • \$\begingroup\$ How are you calling AddCar? \$\endgroup\$ – user106170 Nov 2 '17 at 14:59
  • \$\begingroup\$ @AytAyt addCar.AddNewCar(data2); \$\endgroup\$ – MortenMoulder Nov 3 '17 at 12:59
  • \$\begingroup\$ Ok, my question is more, where did you put that line, and how do you call it. What is the script attached to? \$\endgroup\$ – user106170 Nov 3 '17 at 14:32
  • \$\begingroup\$ 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. \$\endgroup\$ – user106170 Nov 12 '17 at 17:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.