- Home /
Pass class and component reference from inside class
How do I fill out the variable newGameObject.operator? Game has many buildings and many product objects.
The problem I have is that no matter how I do it I run into a conflict.
Functions outside a class cannot be called from within a class.
transform.GetComponent does not work inside a class
Tried using a static class as a go between, but cant pass both needed class references to it anyway
Tried having a UnitInfo.operatorScript reference as shown commented, but it stays null
building game object operatorScript.js
//Variable declarations etc
function Start(){
for (var i : int = 0; i < 9; i++){
Units[i] = new UnitInfo();
//Units[i].operatorScriptReference = this; //Stays always null
}
}
class UnitInfo(){
var cost : float = 0.0;
var stock : int = 0;
//var operatorScriptReference : operatorScript;
function Init(){
newGameObject = Instantiate......etc
newGameObject.AddComponent(gameProduct);
newgameObject.operator = ?????
newGameObject.unit = this;
}
}
product gameobject gameProduct.js
var operator : operatorScript;
var unit : UnitInfo;
//function start()
//etc etc
Answer by Jamora · Feb 25, 2014 at 09:22 AM
The easiest way would seem to be to pass a reference to the constructor of the nested class. This case, the Init()
method could suffice, assuming operatorScript calls it.
//in operatorScript
Units[i] = new UnitInfo();
Units[i].Init(this);
//in UnitInfo
function Init(baseClass : operatorScript){
newGameObject = Instantiate......etc
newGameObject.AddComponent(gameProduct);
newgameObject.operator = baseClass; //<---
newGameObject.unit = this;
}
According to all logic, this should work. I have not tested it though.
Thanks a lot, passing it through Init worked.
Btw if this questions keeps changing name I am not constantly rena$$anonymous$$g it. I did rename it once, and ever since it keeps changing title in the question list. But only listed once in my profile.
Your answer
Follow this Question
Related Questions
arrays and references - a bit puzzled here 1 Answer
UnityScript - Class reference 1 Answer
Your "own" structs ... are they indeed passed by value? 1 Answer
Unity4, Unityscript added "ref" or "out" keyword? 1 Answer
NullReferenceException: Object reference not set to an instance of an object - MonoBehaviour 2 Answers