FindWithTag Random does not work

zodd

New member
public override TaskStatus OnUpdate()
{
if (random.Value) {
var gameObjects = GameObject.FindGameObjectsWithTag(tag.Value);
if (gameObjects == null || gameObjects.Length == 0) { return TaskStatus.Failure; }
storeValue.Value = gameObjects[Random.Range(0, gameObjects.Length)];
} else {
storeValue.Value = GameObject.FindWithTag(tag.Value);
}

return storeValue.Value != null ? TaskStatus.Success : TaskStatus.Failure;
}
The above is your original code for FindWithTag. In this code, Random.Range always returns 0. This seems to be because you have not explicitly typecasted gameObjects as GameObject[]. I was not aware of that limitation, but when I correct this, everything works as expected.

I've noticed when debugging your code that you frequently define variables using var when an explicit typecast could be used instead. Aside from causing this issue, it also makes your code a lot harder to follow, which is annoying for consumers, or me at least lol. Something to think about going forward.
 
var is switched with the variable type at compile time so there no need to apply a casting. I just tried the task and it worked without any changes. I've attached my sample scene - you can see the Test GameObject is assigned.
 

Attachments

Back
Top