Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Call method from another script

Discussion in 'Scripting' started by A_The_Great404, Jun 24, 2023.

  1. A_The_Great404

    A_The_Great404

    Joined:
    Oct 27, 2022
    Posts:
    5
    So i need to call a method in another script in a onpointerclick method i tried it like this:
    MyScript script = new MyScript();
    script.MyMethod();

    but then i always get a null reference error. I already tried someother ways like creating a global variable in my script and getting MyScirpt with GameObject.Find("MyGameObject").GetComponent<MyScript>(); but then even though the gameobject exists the code cant find it. It would be great if some one could help me since im trying to do this for about 2 to 3 days now. Thank You for your help :)
     
  2. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    510
    MyGameObject.GetComponent<MyScript>().MyMethod();
     
    A_The_Great404 likes this.
  3. A_The_Great404

    A_The_Great404

    Joined:
    Oct 27, 2022
    Posts:
    5
    thank you man had to change it a bit but now it finaly works