- Home /
Choosing a random object with a certain tag
Okay so here is the problem, I'm quite new with Unity and I need help.
I have 6 objects in my scene called 'Slab' and every slab has a tag 'Slabs'. What I need the script to do is to choose ONE of them and then destroy it.
GameObject[] Slabstlist;
Slabslist() = GameObject.FindGameObjectsWithTag("Slabs");
That is how I think I should do it but I get an error, (error CS0131: The left-hand side of an assignment must be a variable, a property or an indexer)
After that I'm not sure how I should continue, I've been looking for similar questions and only found one but there was no answer so if anyone is able to help me thank you :)
Due to -1 Answers bug, OP reply got stuck in the queue and disappeared from QA forever
Compiled without errors :) There is something missing but I'll figure that out myself!
Thank you for the quick and useful answers!
GNGification
Answer by Loius · Oct 23, 2013 at 05:51 PM
Take out the () next to Slabslist, and spell it correctly (you have two different spellings there).
A random one would be Slabslist[Random.Range(0,Slabslist.Length)]
To add to this, () is a specific operator meaning "call this as a method with no arguments" (by adding values between the brackets, you can call methods with arguments). Since the results of method calls are not variables, you cannot assign to them, so writing: $$anonymous$$ethod() = ...
just doesn't make sense. On top of that, Slabslist
(or, as you've defined it, Slabstlist
) is not a method anyway, it's a variable, and so doesn't need those brackets, because you're not calling anything.
Answer by CupOfMayo · Oct 23, 2013 at 05:51 PM
In JS i think that should work:
var Arry : GameObject[];
var randomNumber : float;
function Start()
{
Arry = GameObject.FindGameObjectsWithTag("Slabs");
randomNumber = Random.Range(0,Arry.Length+1);
Destroy(Arry[randomNumber]);
}
however i am not sure, I didnt tested that out :)