- Home /
Can't access enum property of an instantiated prefab.
Before you direct me to: http://docs.unity3d.com/Documentation/Manual/InstantiatingPrefabs.html I could not find what I'm looking for.
And there are others that asked it too:
http://answers.unity3d.com/questions/21233/setting-properties-when-instantiating.html
http://answers.unity3d.com/questions/235943/instantiated-object-script-properties.html
But, I just don't understand it well enough due to my own lack of experience (just 2 weeks into C#) to solve my problem.
I decided that, instead of making a whole bunch of different prefabs, I just make one prefab that has a material array property and enum property.
I want to instantiate the prefab, then call a method on the instantiated gameobject to change the enum property and change it's material. I can't seem to figure out how to use GetComponent on the instantiated gameobject to do those two things.
Here is the code attached to the prefab I instantiate.
public class PowerUpScript : MonoBehaviour {
public enum EPowerUpType{Type1,Type2,Type3,Default}
// powerUpType is set to Default in the unity inspector, it needs to be changed in the other class.
public EPowerUpType powerUpType;
// The inspector has 3 materials attached to this array.
public Material[] powerUpMaterial;
void SetPowerup(int i){
// powerUpType = EPowerUpType[i];
GetComponent<Renderer>().material = powerUpMaterial[i];
}
}
This wont actually work, I commented out the powerUpType = EPowerUpType line because I have no idea how to specify it. I know enums store data as integers (Typ1=0, Typ2=1) but I can't seem to set EPowerUpType.i nor EPowerUpType[i].
Here is a snippet of the code that handles instantiating the prefab, which should also change the properties.
switch(brickType){
//...
case EBrickType.Chest:
GameObject powerup = (GameObject)Instantiate(powerupPrefab, transform.position, transform.rotation);
PowerUpScript powerUpScript = powerup.GetComponent<PowerUpScript>();
powerUpScript.
break;
}
But when I want to call powerUpScript.SetUpgrade(int); I just don't get the option to do so. Now I know that the Instantiate function returns a reference to what was just created, but apparently I'm doing something wrong here. It might be better to just change them to different prefabs, but I'm doing this to learn C# and unity so I might as well see how this way would work.
You don't show a method by that name in powerUpScript, if you mean SetPowerup you need to make it public void SetPowerup
Answer by NoseKills · Apr 27, 2014 at 12:04 AM
1) You should be able to just cast it
powerUpType = (EPowerUpType)i;
GetComponent<Renderer>().material = powerUpMaterial[i];
and reverse
int intValue = (int)EPowerUpType.Type2;
2) You can't call void SetPowerup(int i)
because it's not public. Make it public void SetPowerup(int i)