Change property value of prefab instance


This is a beginners question:

I have a prefab with a script named OnClickAction containing a field (Hitpoints field).

public int HitPoints;

In this scripts Update function I sometimes update the HitPoints.

I clone this prefab programmaticaly in another script named Generator (in an array).

GameObject go = (GameObject)Instantiate(prefab, new Vector3(xIndex, yIndex, zIndex), new Quaternion(1f,1f,1f,1f)) as GameObject;

My goal is to increment the value of HitPoints of an instance of a prefab when its clicked (the code for this is in OnClickAction in the Update)

    if (Input.GetButton("Fire1"))
        //Hit, update hit points.

but what happens is that the HitPoints on all clones increments (and not on a specific prefab instance).

How can I fix this behavior.
There is no “static” definintion of the HitPoints field.


The script is there on all clones, so the if-statement will be run on all clones. Hence, all of your clones will run the code within.

What you probably want is to use the function OnMouseDown.

This will only run when you click an object’s collider.

private void OnMouseDown()