I have a class that is an event manager, which is notifying other scripts of touch events. However, the problem is that while the first public static event - SendInteraction - works, the second event, SendDrag, does not seem to be sending the position to the subscribed class. Instead, it just prints a null reference error.
"NullReferenceException: Object reference not set to an instance of an object TouchScreenManager.Update () (at ../TouchScreenManager.cs:47)"
I have tried making the TouchScreenManager class a Singleton and removing references to the events as static, and instead creating new instances in each subscribed class in Awake() but that doesn't work either. How can I fix it?
public class TouchScreenManager : MonoBehaviour
{
#region events
public delegate void SendInteraction(GameObject item);
public static event SendInteraction MoveScene;
public delegate void SendDrag(Vector2 position);
public static event SendDrag Drag;
#endregion
private Vector3 startPos;
private Vector2 startPosition;
private WaitForFixedUpdate waitForFixedUpdate = new WaitForFixedUpdate();
void Awake()
{
EnhancedTouchSupport.Enable();
TouchSimulation.Enable();
}
void Update()
{
if (Touch.activeFingers.Count == 1)
{
var touch = Touch.activeTouches[0];
if (touch.phase == TouchPhase.Began)
{
startPosition = touch.startScreenPosition;
startPos = Camera.main.ScreenToWorldPoint(touch.screenPosition);
DragAndDrop(touch);
CheckForInteraction(touch);
}
else if (touch.phase == TouchPhase.Moved)
{
Debug.Log("from the touch screen manager:" + touch.screenPosition);
Drag(touch.screenPosition); // PRINTS FINE HERE
}
}
}
This script is subscribed to this event.
public class LineGenerator : MonoBehaviour
{
public GameObject linePrefab;
Line activeLine;
Vector2 capturedScreenPos;
private void OnEnable()
{
TouchScreenManager.Drag += DrawLine;
}
private void OnDisable()
{
TouchScreenManager.Drag -= CompleteLine;
}
void DrawLine(Vector2 position)
{
GameObject newLine = Instantiate(linePrefab);
activeLine = newLine.GetComponent<Line>();
capturedScreenPos = position;
Debug.Log("from the line generator: " + position); // NULL REF HERE
}
}
````