This one is strange. I’ve got a for loop set up to add each gameObject of an array to another array. I have a print check to make sure it’s working, so I know the for loop is iterating, but it keeps on adding the same gameObject to the array. It makes absolutely zero sense.
var newTargets : List.<TargetClass>;
var nullTarget : TargetClass;
public class TargetClass{
var target : GameObject;
var threat : float;
}
function Start(){
FindTarget();
}
function FindTarget(){
for(var p : GameObject in GameObject.FindGameObjectsWithTag("Friendly")){
nullTarget.target = p;
print(nullTarget.target);
newTargets.Add(nullTarget);
}
}
So let’s say we have two objects called “Man 01” and “Man 02.” If we try to add them to newTargets, it will just add “Man 02” twice, yet it will print “Man 01”, and then “Man 02.” So the nullTarget says that it’s switching, but when I check the editor, it hasn’t.
Somebody please help me. This is driving me insane!
You have to create an instance of your TargetClass for each target. It’s a reference type. If you just create one instance, you will be using this one instance all the time and add the same reference to your List.
Btw: nullTarget i badly worded and shouldn’t be a member variable.
public class TargetClass
{
var target : GameObject;
var threat : float;
}
var newTargets : List.<TargetClass>;
function Start()
{
FindTarget();
}
function FindTarget()
{
for(var p : GameObject in GameObject.FindGameObjectsWithTag("Friendly"))
{
var item = new TargetClass();
item.target = p;
print(item.target);
newTargets.Add(item);
}
}
you’re setting the “target” data member of nullTarget, but never changing nullTarget itself, just it’s data member “target”
but on the last line you just add nullTarget, should be nullTarget.target I guess
EDIT:
function FindTarget(){
for(var p : GameObject in GameObject.FindGameObjectsWithTag("Friendly")){
nullTarget = p.GetComponent(TargetClass);
print(nullTarget);
newTargets.Add(nullTarget);
}
this way you are passing each object, instead of the same one each time