How to enable only one script (shared by multiple gameobjects) at a time/click ?
So I have two scripts each attached to a few blocks (gameObjects). Scripts are: DragScript and CheckWin
DragScript actually enables the CheckWin script when the gameobject its attached to is clicked.
public class DragScript : MonoBehaviour {
public CheckWin scriptCheckWin;
public static bool mySwitch = true;
void OnMouseDown()
{
if (Physics.Raycast(ray, out rayHit))
{
if (rayHit.collider.tag == "Puzzle")
{
scriptCheckWin = gameObject.GetComponent<CheckWin>();
if (mySwitch == true)
{
scriptCheckWin.enabled = true;
mySwitch = false;
}
else {
scriptCheckWin.enabled = false;
mySwitch = true;
}
}
}
}
This lets me turn enable and disable the scriptCheckWin on the gameObject -by clicking it- the dragscript is attached to (like it should)
The problem is if I click another gameobject its scriptCheckWin is enabled and the previous one I just clicked is also enabled. I only want one scriptCheckWin to be enabled when clicked to be enabled for efficiency. Just to let you know there will be more than 2 gameobjects.
Thanks in advance.
Answer by AR_Rizvi · Jan 28, 2017 at 05:46 AM
Hope this Will help Edited your Code
public class DragScript : MonoBehaviour {
public CheckWin scriptCheckWin;
public static bool mySwitch = true;
public static Gameobject lastCheckWin;
void OnMouseDown()
{
if (Physics.Raycast(ray, out rayHit))
{
if (rayHit.collider.tag == "Puzzle")
{
if(lastCheckWin ==null)
{
scriptCheckWin = gameObject.GetComponent<CheckWin>();
lastCheckWin = gameObject.GetComponent<CheckWin>();
}
else
{
lastCheckWin.GetComponent<CheckWin>().enabled = false;
lastCheckWin = gameObject.GetComponent<CheckWin>();
}
if (mySwitch == true)
{
scriptCheckWin.enabled = true;
mySwitch = false;
}
else {
scriptCheckWin.enabled = false;
mySwitch = true;
}
}
}
}
While I do think you are possibly on the right track (in terms of logic) it does not seem to work for me as the gameobject cannot be null. I changed it to be a CheckWin (script) variable but even then it does not accept null.
$$anonymous$$y sincere thanks to the both of you guys. You saved me a lot of time and head scratching. I can not thank you enough.
Your answer
Follow this Question
Related Questions
Best practices to select a group of gameObjects 1 Answer
Unity5/C# beginner here! Need some scripting help :) <3 1 Answer
How to assign a gameobject/transform to a prefab 0 Answers
How to toggle elements within a prefab in Unity 0 Answers
How do I enable/disable components in a prefab from another script? 1 Answer