Search Unity

Call a function from another script?

Discussion in 'Scripting' started by getmyisland_dev, Jul 9, 2021.

  1. getmyisland_dev

    getmyisland_dev

    Joined:
    Dec 22, 2020
    Posts:
    100
    I want to call a function from another script that is attached to a different game object. I've been searching for answers for a while now and every solution I found on the internet didn't work for me. I always get an error when I try to type the function name.

    I tried:
    Code (CSharp):
    1. GameObject player = GameObject.Find("Player");
    2.         PlayerManager other = (PlayerManager)player.GetComponent(typeof(PlayerManager));
    3.         other.ReportBody();
    and:
    Code (CSharp):
    1. PlayerManager playerManager = player.GetComponent<PlayerManager>();
    2.         playerManager.ReportBody();
    I want to call the ReportBody function. This function is located in the PlayerManager script that is attached to the player object.

    Are there any more ways in handling this. If I press "E" on the keyboard this function should be called.

    -Max
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    First of all, when you ask for help, and you mention an error happening, please include the error itself.

    Is ReportBody marked as "public" in your code? If not, you won't be able to call it, so do that
     
    getmyisland_dev likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726