- Home /
How to check an entire list and apply conditions.
Hello and apologizes regarding the title
I have no idea how to put this better. My question is how to manage the following better:
I have 15 game objects instantiated randomly. Each object when clicked, will direct you to a scene (15 scenes in total)
How to attach each load scene to each game object efficient when clicked ?
My code idea is this :
void SettingUpLocations()
{
if(Input.GetMouseButtonDown(0))
{
//SETUP EACH LOCATION
if (clickedGmObject.name == "BattleLocation1(Clone)")
{
Application.LoadLevel ("FirstLevel");
}
}
}
I will iterate this 14 more times. I am pretty sure there is a more effective way of doing this. Any ideas ?
BTW I also have a list of the spawned prefabs made like this :
prefabTransforms.Add(Instantiate(spawnThis[i].transform, spawnPoints[r].transform.position , spawnPoints[r].transform.rotation) as Transform);
Answer by cregox · Jun 04, 2013 at 06:44 PM
You can't use Input.GetMouseButton
and expect it will know which object you clicked. It gathers mouse event regardless where it is clicking.
Make a class like this and name it `SettingUpLocations.js` (or whatever you wish):
#pragma strict
public var levelName = "";
function OnMouseUp () {
Application.LoadLevel(levelName);
}
Add it to each of your game objects and set Level Name
as you wish in the Inspector. Be sure the objects have colliders on them.
P.S.: You could name the question something like "How to check for mouse clicks on many different objects". Also, next time, try researching and looking at code on wiki first. Lots to learn there! ;-)
You indirectly gave me ideas though my problem wasn't that the code wasn't working. I was using ray casting so I was identifying the objects correctly.
Putting this small script on each object is better than verifying 15 'if's in one method.
Thanks a lot!
PS: Also changed the title to something more correct.
@primus88 Well, you didn't mention ray casting. On$$anonymous$$ouseUp
does have its caveats. It won't work for touching interfaces, for one. But there is a script to fix that, which does use Input
and Raycasting
.
Also, if you really want it to behave as a button, you may want to use `On$$anonymous$$ouseUpAsButton` ins$$anonymous$$d.
I also think putting the script on each object is better - as stated on the answer! No idea what indirect ideas I gave you there.
And I haven't noticed the title change.
I was the referring to the idea with using a small script for each object. It is good.
I changed the title.
Your answer
![](https://koobas.hobune.stream/wayback/20220613103522im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
conditional spawning 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
question about if statement order of execution 2 Answers
Split a cube into several pieces? 1 Answer
scripting question 3 Answers