Android App - Touch - Function call from another object

Hello,

I have a scene with 36 spheres. All with a collider. And a wall “mainwand”, that’s a plane-Object. This contains the game’s “control script”. Each sphere has its own script "kugel1skript … kugel36skript. The whole thing is an Android app. When I touch a sphere, the number should be reported to the control script via a function call. Unfortunately, this also works when I touch another place.
here is the kugel1skript

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Kugel1skript : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject mainwand;
    public Mainskript1 mainscript;
    
    void Start()
    {
          
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
        {
            mainscript.Klickbehandler(1);
            print("touch auf 1.te");
        }
    }
}

and now the controlskript from the plane:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Mainskript1 : MonoBehaviour
{
    // Start is called before the first frame update
    
      void Start()
    {
        
    }    
 public void Klickbehandler(int nr)
    {
        print(nr);

    }


    void Update()
    {
      

    }
 

}

what’s my failure? many thanks

Update() runs on EVERY object, not just the one you touch.

This function might help you:

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html

Read the docs to see the criteria for what causes Unity to call that method.

2 Likes

Your function gets called any time you touch the screen at all. You need to determine if the touch is on a sphere, so that’s the OnMouseDown that Kurt-Dekker said (the sphere has to have a collider). Note that this will handle only the first touch (no multitouch), it’s treated like a mouse button. Multitouch will take some more fiddling.

Instead of a separate script for each sphere, you can just use one. Add this variable:

public int sphereNumber;

Then in the Inspector for each sphere, set the number to correspond to the sphere. (There are even slicker ways, but this at least uses only one script.) So later in your code you’d have

mainscript.Klickbehandler(sphereNumber);
print(“touch auf " + sphereNumber " +.te”);

Hope that helps, it’s important to see where you can re-use code with variables, prefabs, etc.