So, I have a MapBuilder object that has a script which places random stars on the 2d plane. While generating each star, I want to give them some variables to make them unique, for example their color or size.
I made a script that gets added to the new star objects that stores those variables, but I need to change them from the MapBuilder script.
The stars start as a new empty GameObject. I then add the script via the AddComponent function. Here is where I encounter my problems: I try to change the variable of the scripts, but Unity returns an error: starColor is not a member of UnityEngine.Component.
I have seen other people sing this method for chnaging variables so i don’t know why it is not working.
This is the script in the MapBuilder object:
#pragma strict
var amtStars = 1;
function Start () {
for (var i = 0; i < amtStars; i++){
var star = new GameObject("Star" + (i + 1));
var inst = GameObject.Find("Star" + (i + 1));
inst.AddComponent("starControler");
var script = inst.GetComponent("starControler");
script.starColor = "red";
//star.transform.position = transform.position;
//star.AddComponent("SpriteRenderer");
}
}
This is the script in the new star, it is just there to store the variable:
#pragma strict
public var starColor : String;
function Start(){
Debug.Log(starColor);
}
By the way, I'm really not very good at UnityScript. If that doesn't work, try using the GetComponent method like they do in the docs, [here][1]. [1]: http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
– BasteThanks for your input, but the method you proposed does not work for me, i now get the error: The name 'starControler' does not denote a valid type ('not found'). Also the GetComponent method gave me the same error as before
– AvanakThe "not a valid type" error is because the compiler can't find a type named "starControler". Replace it with the actual name of the script you're adding.
– BasteAh thanks, i made a typo. Stupid me! Anyway it works, many thanks!
– AvanakThat's why it's better to use generics instead of the string form in just about all cases.
– Kiwasi