- Home /
Other
Calling A Function Once
I have a few functions that can resize Unity's built-in array system, however I'm having a problem where the elements are added repeatedly, I just the element to be added once. The answer to this might be simple, but I can't figure anything out. I tried using an if statement to test a variable that checks if the element has been added but this doesn't work very well, in addition I don't want to have to make a new variable for every time I want to use this function. I also have a remove function, I'll post that as well in-case the functions need specific ways to do this.
The Add Function
static function AddGO(arr : GameObject[], obj : GameObject)
{
var tmpArr : GameObject[];
tmpArr = arr;
arr = new GameObject[tmpArr.length +1];
arr[arr.length -1] = obj;
for(i = 0; i < arr.length -1; i++)
arr[i] = tmpArr[i];
return arr;
}
The Remove Function
static function RemoveGO(arr : GameObject[], obj : GameObject)
{
var index = -1;
for (var i = 0; i < arr.length; i++)
{
if (arr[i] == obj)
{
index = i;
break;
}
}
if (index == -1) // the element wasn't found
return arr;
var tmpArr = new GameObject[arr.length - 1];
for(i = 0; i < index;i++)
tmpArr[i] = arr[i];
for(i = index+1; i < arr.length;i++)
tmpArr[i-1] = arr[i];
return tmpArr;
}
What I'm using to call them:
modArray = array; modElement = element; modArray = AddGO(modArray, modElement); array = modArray;
Removing is the same thing but just with Remove instead of Add.
If you call a function once, it's only called once; nothing will make it be called multiple times unless you do that yourself. You should really use List ins$$anonymous$$d of doing this though. If you absolutely have to resize a built-in array for some reason, then use System.Array.Resize.
the code I'm using to call it is inside of a function thats called from an update function
Well, if it's in Update then I guess it's being called every frame? In that case you don't want to use Update, or at least add some logic to prevent it being called every frame.
That's the problem, this is called many times and making logic for it being called every time is a bit tedious (as in every time I want to add an element). The reason I don't want to use lists is because I need this to be as fast as possible.
You're not gaining any speed by using a GameObject array ins$$anonymous$$d of a List of GameObjects; in fact you're losing speed whenever you add/subtract, because List can do this much more efficiently than this code.
Follow this Question
Related Questions
What's wrong with this code? 1 Answer
Calling a function only once in Update 3 Answers
Efficient way for calling a function once 3 Answers
Calling Functions from another Script 3 Answers