I am trying to add my script from a game object to another game object by trying to add component but I want it to have the same custom variables. I am wondering if I could add a component to the game object and change the variables to match the other game object. Here is my script so far…
GameObject cpuClone = Instantiate (Cpu, new Vector3 (6, -2, 0), Quaternion.identity) as GameObject;
cpuClone.GetComponent<SpriteRenderer> ().sprite = player2;
cpuClone.name = Cpu.name;
PlayerCPU cpu = cpuClone.AddComponent<PlayerCPU>();
cpu = transform.FindChild("Abilities").GetComponent<PlayerCPU>(); //Trying to have the same script as the gameobject Abilites
You need to set the value you need one by one.
I see 2 ways of doing it, the second is IMO better.
The first:
cpuClone.AddComponent<PlayerCPU>();
cpuScript = cpuClone.GetComponent<PlayerCPU>(); //cache it like this so you won't need multiple GetComponent
cpuScript.value1 = Cpu.value1;
cpuScript.value1 = Cpu.value2;
//etc...
//your values have to be public so it's not ideal
The second is having a function in your class like this:
public void GetValues(int _value1, string _value2) //as many parameters as values you need
{
value1 = _value1;
value2 = _value2;
//etc...
}
Then call it after instantiating like this:
cpuClone.AddComponent<PlayerCPU>();
cpuClone.GetComponent<PlayerCPU>().GetValues(value1, value2) //etc...
I wonder why you need to add the component on run, wouldn’t it be better to have it in the prefab?