- Home /
Instantiate script then edit its variables
I'm new in unity and wasn't able to figure this out. My question is a bit hard to explain but i'll do my best.
I'm creating the player information struct to attach it to my prefab of player controller.
I want to instantiate the script, then change it's variables so I can set them based on the GUI and add them later to my prefab with addComponent.
But unity doesn't like "new script" I'm not really sure how to do this. I've been wandering around Instantiate() and clone tutorials but I always end up with some error.
public CharacterChart playerChart; // (global)
CharacterChart tempChart; // (local)
tempChart = Instantiate(playerChart) as CharacterChart;
Currently error says the thing(clone) i want to instantiate is null, I suppose this is because I haven't initialize it.
I'm using c#
thanks
Answer by PedramAUS · Feb 17, 2013 at 03:13 PM
Instantiate is for cloning an object for instance a prefab. If you have a script, you shouldn't instantiate it, you just need to add it as a component to an object and the variables that you want to edit should be public and static, then you have access to those variables in the second script.
CharacterChart playerChart = AnObject.AddComponent<CharacterChart>();
PlayerChart.APublicStaticVariable = "A Value";
PlayerChart.DoSomething();
the problem is that i can only add the script as a component after I create the PController. But since the PController is only created after the script is set via GUI, I cannot add it as a component
You should have a main controller in your game and protect it from being destroyed. There you should manage all these stuff such as creating an object (PController) and assigning components (CharacterChart).
I was able to do a "fix" on my problem but at cost that now while in GUI the playerController is active with camera and controls. Is there a way to disable the camera and movements? I cannot disable it totally because then i don't seem to be able to access values of the script inside him.
Answer by GamingNewBie · Feb 17, 2013 at 03:09 PM
For better understanding of Instantiating Game Objects, follow link
docs.unity3d.com/Documentation/Manual/InstantiatingPrefabs.html
secondly for adding script components dynamically
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.AddComponent.html
hope it helps.