- Home /
Static Variable Not Assigning Half The Time?
I created a simple static variable on many of my objects to track how many are made. Sounds simple enough... but they don't work outside the constructor! What am I missing here? The frustrating part is the code works for Corporation, but the EXACT SAME CODE doesn't work in Mission.
Stripped down code
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Corporation : MonoBehaviour
{
static public int corporationsMade=-1;
//Variables
public int corpID;
public Corporation()
{
corpID = ++Corporation.corporationsMade; //increment made count, then assign number
}
}
THAT ALL will "work" as long as it's in that code block, in that the ID and the objectsMade are both increasing... however, when I create a corporation outside like so...
public class CorporationFactory : MonoBehaviour
{
//Variables
public List<Corporation> corpMarket;
Corporation GenerateCorporation ()
{
Corporation newCorp = (Corporation) Instantiate(corpPrefab);
newCorp.transform.parent = CorporationFolder.transform;//child to CorpFolder
newCorp.corpManager = corpManager;//give reference to corpmanager
newCorp.name = string.Format("{0}:{1}", newCorp.corpID, newCorp.corpName);//name object after id:corpName
return newCorp;
}
That doesnt work! The static variable is still increased, but the object's ID is 0.
could you simply print out newCorp.corpID using Debug.Log ?
Answer by sintua · Feb 27, 2013 at 08:16 PM
Found out the answer myself: Monobehaviors do not play nice with constructors... I just didn't think it's "partially" work like this. After I put the static variable increment in the awake function it worked fine.