Daniele
Daniele

Reputation: 1

Variable in prefab's script doesn't change in my own method

I have a strange problem with my script attached on a prefab object and attached to a button. I tried to search this problem, but without success.

I will explain a very simple example. I have a prefab PlayerPrefab that is created by a script PlayerSpawn through the instruction:

Instantiate (playerPrefab, transform.position, Quaternion.identity);

So, when the game starts, a new instance of PlayerPrefab is created.

Attached to the prefab there is a script with some private variables (for simplicity I write a simple script code):

public class ShipClass : MonoBehaviour {
    float speed;
    int count;

    void Start () {
        speed = 0;
        count = 0;
        Debug.Log ("Start executed, speed = " + speed);
    }   
    void Update () {
        Debug.Log("speed in Update = " + speed);
    }
    public void Push ()
    {
        speed = 50;
        count++;
        Debug.Log("speed in Push = " + speed);
        Debug.Log("count = " + count);
    }
}

Then i created a UI Button, with OnClick event, attaching the prefab object and calling the method Push().

The behavior is very strange: Once i start the game for the first time, the printed speed from Update() and Push() methods is 0. But when I start to click the button in the UI, the speed in Push() method becomes 50, but Update() still prints 0, as if we had two different variables speed.

The second thing is that pushing the button, the count variable increments. When I stop the game and restart it, count variable doesn't reset in the Start method (even if Start() is executed, seeing the printing log), but starts from the last value in the previous run. Also, we have the same behavior like the speed variable: in Update(), count remains 0, in Push() counts continues to increment, like we have two different "count" variables.

I know it is due to the prefab object, but I don't know how the variables behave differently in Update() and own created methods.

Thanks in advance for the help.

Upvotes: 0

Views: 273

Answers (1)

Pluto
Pluto

Reputation: 4061

Right now you are calling Push on the instance of ShipClass attached to the prefab. What you want is the ShipClass instance attached to the instantiated object.

GameObject player = Instantiate(playerPrefab, transform.position, Quaternion.identity);
ShipClass shipClass = player.GetComponent<ShipClass>();
button.onClick.AddListener(shipClass.Push);

Also make sure in the inspector to remove the prefab from the button's OnClick() list.

Upvotes: 1

Related Questions