My problem is really simple but I do not know how to search for this and actually find a good topic, so I am sorry if this is a double post.
I have a scene with multiple identical levers which all use one script:
using UnityEngine;
public class LeverScript : MonoBehaviour {
public GameObject objectToUse;
public void UseObject()
{
Debug.Log("Using lever!");
Destroy(objectToUse);
}
}
I also have an USE button on my canvas which calls my UseObject() from the lever. This is supposed to deactivate a forcefield.
using UnityEngine;
using UnityEngine.EventSystems;
public class JoyButtonUse : MonoBehaviour, IPointerUpHandler, IPointerDownHandler
{
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("Joybutton Used");
FindObjectOfType<LeverScript>().UseObject();
}
public void OnPointerUp(PointerEventData eventData)
{
throw new System.NotImplementedException();
}
}
The problem is that even if in interface there are different forcefields attached to each lever as objectToUse, they all call just one and it is really impossible for me to understand why.
Update:
I tried to change my code as follows:
The lever script:
using UnityEngine;
public class LeverScript : MonoBehaviour {
public GameObject objectToUse;
private void Update()
{
if (JoyButtonUse.usePressed)
{
UseObject();
}
}
public void UseObject()
{
Debug.Log("Using lever!");
Destroy(objectToUse);
}
}
and the use button script to this:
using UnityEngine;
using UnityEngine.EventSystems;
public class JoyButtonUse : MonoBehaviour, IPointerUpHandler, IPointerDownHandler
{
public static bool usePressed = false;
public void OnPointerDown(PointerEventData eventData)
{
usePressed = true;
Debug.Log("Joybutton Used: " + usePressed);
}
public void OnPointerUp(PointerEventData eventData)
{
usePressed = false;
Debug.Log("Joybutton released: Pressed is: " + usePressed);
}
}
public void UseObject()
{
Debug.Log("Using lever!");
Destroy(objectToUse);
}}
so that my button does not know about the in game objects.
But now, all objects are destroyed when using any lever.
How can I make those scripts work independently while being basically the same?
Or is any better optimal solution for my needs?