Hi,
I just found out that I can use Physics.RaycastNonAlloc to prevent memory allocation. I am using a script to manage the input in my game and everything works fine except for allocating memory each time a mouse or touch input is made. The thing is that I can’t find a single script even in Unity’s documentation on how to use Physics.RaycastNonAlloc, so if someone could help me I’d be grateful. I just need to convert this script using Physic.RaycastNonAlloc and not Physics.Raycast to execute a function in my game.
Here is the script I am using now :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TouchInput : MonoBehaviour {
// Singleton
private static TouchInput instance;
// Construct
private TouchInput() {}
// Instance
public static TouchInput Instance {
get {
if (instance == null)
instance = GameObject.FindObjectOfType (typeof(TouchInput)) as TouchInput;
return instance;
}
}
public LayerMask touchInputMask;
private RaycastHit hit;
Ray ray;
GameObject recipient;
public delegate void OnClickEvent(GameObject g);
public event OnClickEvent OnTouchDown;
void Update ()
{
#if UNITY_EDITOR
if (GameControl.control.GetComponent<GamePlay>().isPlaying)
{
if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0) )
{
ray = GetComponent<Camera> ().ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, touchInputMask))
{
recipient = hit.transform.gameObject;
}
if (Input.GetMouseButtonDown(0))
{
OnTouchDown(recipient);
}
}
}
#endif
if (GameControl.control.GetComponent<GamePlay>().isPlaying)
{
if (Input.touchCount > 0)
{
foreach (Touch touch in Input.touches)
{
ray = GetComponent<Camera> ().ScreenPointToRay (touch.position);
if (Physics.Raycast (ray, out hit, touchInputMask))
{
recipient = hit.transform.gameObject;
}
if (touch.phase == TouchPhase.Began)
{
OnTouchDown (recipient);
}
}
}
}
}
}
You can also see the image below to see how much memory is this script allocating each time I click over the object which has the same layer as “touchInputMask”.
If you need more information I can share it with you.
Thank you,
Gerald.