so here's what I'm trying to do:

1) I have a prefab called bloby, just a simple sphere that contains a Bloby class script (will explain later).

2) I need to instantiate 10 blobies in the screen, but each bloby has a different speed, so I created a class called Bloby:

Code (CSharp):

public class Bloby : MonoBehaviour

public float speed;
public GameObject body;

public Bloby(float s, GameObject ga)
    this.speed = s;
    this.body = ga;

public void Instant(float xPos, float zPos)
    GameObject instance = Instantiate(this.body) as GameObject;
    instance.transform.position = new Vector3(xPos, 1, zPos);


3) Since I'm instantiating a gameobject, when I create a Bloby object, I pass the prefab as a parameter and instantiate.

4)This works fine, my Bloby gets instantiated in the screen when I call Bloby bloby = new Bloby(10, character); (character being the gameobject)

5) The weird thing is that when my object gets instantiated, the Bloby script (that is attached to the prefab), stays with the variables value of speed = 0 even though I set it to 10 when I created it and the body variable = null. If I put a Debug.Log(speed) on the Bloby class, it shows 10, but the variable value on the script itself doesn't change.

*Here's the place where I create the Blobies:

Code (CSharp):

public GameObject character;
Bloby bloby = new Bloby(10, character);
bloby.Instant(xPos, zPos);

I'll try to add some pictures to make it easier to understand what I mean. Thanks

1 Answers

mchts On Best Solutions

Do not try to initialize a class derived from MonoBehavior with new keyword. Change your Bloby to this and attach bloby to your prefab:

public class Bloby : MonoBehaviour{
   public float speed;

Then create your instance like below externally(i.e. in another script):

GameObject instance = Instantiate(bloby, new Vector3(xPos, 1, zPos), Quaternion.identity) as GameObject; //bloby is your prefab that you already created
instance.GetComponent<Bloby>().speed = 10;