Hello beautiful people,
I have a prefab with a script attached (see below) which is supposed to detect touch on that object only. When my scene starts for the first time, I instantiate two instances of this prefab. When the player touches that prefab, only the prefab that was touched detects the touch. Excellent. However, if I destroy those two instances and instantiate them again (in my game, I’m now instantiating three instances), all three prefabs detect the touch, rather than the one actually touched.
I would be so grateful if somebody could look at my code and explain what is happening - and how to fix of course
function Update ()
if( Input.touchCount == 1 )
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
var ray : Ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
var hit: RaycastHit;
if( collider.Raycast( ray, hit, 100 ) )
Well, I’m a complete dummy. The problem was the logic I was using in my code - I forgot to reset a variable back to zero before instantiating the next load of prefabs, so they were being destroyed on the first touch, making it look like a problem with collider.Raycast, which it isn’t.
I thought I’d leave this question up because it might be helpful for others who want to detect touch on cloned prefab instances. Most of the touch code on Unity Answers revolves around using Physics.Raycast and detecting the name or the tag of the game object touched. Clearly that’s no good when you’re instantiating multiple copies of a single prefab.
Simply attach the script in the question above to the prefab and when each prefab is instantiated, it will detect touch and you can insert the appropriate code in place of Debug.Log(“hit”); I personally use the Flashbang messenger class to send messages to a ‘controller’ script that handles all the game logic. If you’re not using this messenger class, check it out: http://technology.blurst.com/unityscript-messaging-system/
Hope somebody finds this useful