- Home /
Can't initialise public vars in Inspector (C#)
Summary:
I'm trying to use the Inspector to set a value on a non-static public var, but the game ignores the Inspector and uses only the scripted values.
Intended behaviour:
I have a class named PlayerControls, which calls a class named Shotgun. If I set Shotgun's _ProjectilesPerShot to 10 in the Inspector, the script should instantiate 10 projectiles.
Actual behaviour:
The script ignores the _ProjectilesPerShot value I've set in the Inspector (I am setting it on the prefab itself). The asset variables (sound, prefab) work fine, though.
Initialising _ProjectilesPerShot in the script makes it work, but the Inspector doesn't change this value at runtime. Setting _ProjectilesPerShot = 1 in the script but = 10 in the inspector only instantiates one projectile.
Things I have tried:
I added a Debug.Log in the Shotgun constructor to show the values of projectilesPerShot and _ProjectilesPerShot after assignment. Both values remain unchanged (0 and 0 if uninitialised in the script, n and n if _ProjectilesPerShot = n in the script).
PlayerControls.cs
using UnityEngine; using System.Collections;
public class PlayerControls : MonoBehaviour { public Shotgun shotgun;
void Awake () { shotgun = GetComponent<Shotgun>(); } void Update () { if (Input.GetMouseButtonDown(0)) { shotgun.fire(); } } }
Shotgun.cs
using UnityEngine; using System.Collections;
public class Shotgun : MonoBehaviour { // Inspector-accessible variables. public int _ProjectilesPerShot;
// Inspector-accessible asset variables. public GameObject projectile; public AudioClip fireSound; // Internal variables. private int projectilesPerShot; public Shotgun () { projectilesPerShot = _ProjectilesPerShot; } public void fire () { audio.PlayOneShot (fireSound, 0.05f); for (int i = 0; i<projectilesPerShot; i++) { Instantiate (projectile, gameObject.transform.position, Quaternion.identity); } } }
Any help would be greatly appreciated!
Answer by termway · Jul 24, 2012 at 01:18 PM
Try to use Start() method instead of class constructor
public Shotgun ()
{
projectilesPerShot = _ProjectilesPerShot;
}
=>
public void Start ()
{
projectilesPerShot = _ProjectilesPerShot;
}
Read section 2 & 7 : http://docs.unity3d.com/Documentation/ScriptReference/index.Writing_Scripts_in_Csharp_26_Boo.html
Hope it solve your problem!
Exactly. The deserialization happens after the object has been created. Therefore the constructor is already finished when the serialized value is assigned.
That's also the reason why the docs always tell you to not use the constructor. Use Awake() or Start().
Thank you, this was exactly it! Not sure how I missed that. :/
Answer by MihaPro · Jul 24, 2012 at 03:30 PM
Don`t use constructor for MonoBehaviour derived classes. Use Awake and Start for initialization.