- Home /
Add a temporary variable to an array
So I'm trying to add a temporary variable inside a function to an array. This variable is of a custom made class.
Unfortunately I can't seem to get it to work. The array increases size but when I "call" for the variable it always comes out emtpy unless I declare it outside the function..
Here is the current code where I add the variable:
var pickUpAction : PlayerActions;
function PickUp (selectedObject : Transform){
GoTo(selectedObject);
//Add a pickUpAction
// var pickUpAction : PlayerAction; //this is where I wanted to have the variable so it disappears after being added.
pickUpAction.interaction = PickUpAction;
pickUpAction.selectedObject = selectedObject;
globalActions.Add(pickUpAction);
}
And here is the example of a function that later on uses it:
function DoAction (){
currentAction = (globalActions[0] as PlayerAction);
currentAction.interaction ();
globalActions.RemoveAt(0);
}
and this is the class of the variable:
class PlayerAction {
var interaction : function():void;
var selectedObject : Transform;
var selectedDestination : Transform;
var selectedPosition : Vector3;
};
I'm quite new to programming so sorry if I'm missing the obvious! Any help very appreciated.
Answer by whydoidoit · Jun 21, 2013 at 07:35 AM
I think you are looking for:
var pickUpAction = new PlayerAction();
It works!!! Thank you :) What I don't understand is why it works...What is the difference between:
var pickUpAction : PlayerActions;
and
var pickUpAction = new PlayerAction();
I didn't know about the "new", what difference does it make?
Well the first defines an empty variable and the second actually creates one. I guess you are not using #pragma strict or it would probably not compile.
Thanks for the explanation. I have the #pragma strict at the top and it still compiles. I was only getting the error when executing the function.
Your answer
![](https://koobas.hobune.stream/wayback/20220613104600im_/https://answers.unity.com/themes/thub/images/avi.jpg)