Lists - Default values?

1396194--72178--$list_defaultValue.png

In my Character Selection script I have a list with all the characters you can choose from in my game. I want to set some default values, but they won’t show up in the inspector? How can I do this?

Code:

	[System.Serializable]
	public class Characters {
		public string Name;
		public GameObject _character;

		public enum Race
		{
			Warrior,
			Wizard,
			Elf,
			Necromancer
		}
		
		public Race characterRace;
		
		public int StartingHealth = 100;
		public int StartingMana = 100;
		public int Strength;
		public int Agility;
		public int Constitution;
	}
	
	public List<Characters> characters = new List<Characters>();

As you can see I’m trying to set StartingHealth and StartingMana to 100 by default but that doesn’t work :confused:

reset the values, gear icon in the inspector show this option

Already tried that…

Anyone? =(

Interesting, problem. I see your character in the image is named Warrior, where does this name come from?

The Characters class has no constructor
public Characters () { this.name = … }

The class has at least the implicit default CTor, also the initializers are implemented as constructor logic. Where do the instances in the list come from?

Yeah, and that’s why they are all zero’s

I think I may missunderstand you, but he is using field initializers:

public int StartingHealth = 100;
public int StartingMana = 100;

so this values should not be zero after the CTor completed his work.

1 Like

Huh yeah, I see I was wrong. It seems it’s a problem that’s been about for a while
http://forum.unity3d.com/threads/102042-List-lt-T-gt-variable-initialization-amp-inspector

I’m particularly amused that you can Log from a constructor, and it will log the given values, but still show up as zeros.

public class test : MonoBehaviour {
	public List<c> L;

	[System.Serializable]
	public class c  {
		public int hp;
		public c () {
			Debug.Log( "Making new c" );
			this.hp = 6;
			Debug.Log( "new c, hp is: " + this.hp );
			//Logs a 6 when you increase size
		}
	}
	void Awake () {
		Debug.Log( L[0].hp );
		//Logs a zero
	}
}
1 Like

From this:

public string Name;

:slight_smile:

Ok, so there’s no way setting defaults? Well, it’s not that important anyways - but it would be nice if it could be done somehow…

Have you tried setting them in your constructor rather than initializing the fields?

You can give your SelectCharacter script a Reset() function that will be called when it is first attached, or when you select that option in the Inspector.

The inspector overwrites values of serialized items after construction. For the behavior the you want, you can set values on the constructed Data instances in Start or OnAfterDeserialize.

Take a look here:

2 Likes