I'm a begginner in Unity.
I have a script, which arrange the movement of two game object. I use onm ouseDown. It activates the GameObject where the click happened and let the movement (with keyboard). My problem is if I click the second game object the first one still moves (both of them). How can I turn off the movement for the first object?
void onm ouseDown()
{
if (activeUnit==false )
{
activeUnit=true;
}
else {activeUnit = false;}
}
void Movement (){
if (activeUnit == true)
{//here comes the movement method
Thank you for your help!
CodePudding user response:
If you want to limit the movement to exactly one object you could use a static
instead your bool and go
private static YOURCLASS _currentlyActiveInstance;
void onm ouseDown()
{
if(_currentlyActiveInstance == this)
{
_currentlyActiveInstance = null;
}
else
{
_currentlyActiveInstance = this;
}
}
void Movement ()
{
if (_currentlyActiveInstance == this)
{
//here comes the movement method
}
}
CodePudding user response:
To toggle a variable first you should better use this syntax:
void onm ouseDown()
{
activeUnit=!activeUnit;
}
You can add another function onm ouseUp to Untoggle the unit. So the full code should look like that:
void onm ouseDown() {
ToggleUnit();
}
void onm ouseUp() {
ToggleUnit();
}
void ToggleUnit() {
activeUnit=!activeUnit;
}
Otherwise if you don't wanna use onm ouseUp to untoggle the Unit, you should add an EventListener that untoggle units when clicking