Search code examples
c#unity-game-enginevariables

How can I access another variable I defined in another function?


The Attack() method will be used on a button and a want to define variables at the start but I'm not sure how to do it (Unity 2D):

using System.Collections;
using System.Collections.Generic;
using UnityEditor.SearchService;
using UnityEngine;
using TMPro;

public class DefaultEnemy : MonoBehaviour
{
    public static void DefineVariables()
    {
        int phealth = GameObject.Find("VStorage").GetComponent<VStorage>().phealth;
        int pdamage = GameObject.Find("VStorage").GetComponent<VStorage>().pdamage;

        int ehealth = GameObject.Find("VStorage").GetComponent<VStorage>().ehealth;
    }

    public static void Attack()
    {
        ehealth = ehealth - pdamage
    }

    private void Update()
    {
    }

    private void Start()
    {
        DefineVariables();
    }
}

I've tried a few things like making a method for the variables. I expected this to do something but I just get a different error :/


Solution

  • I don't know anything about Unity, but your question has to do with variable SCOPE. Variables can be accessed from within the block that they're defined, so if you want to access variables from more than one method, they need to be defined outside the scope of a single method (at the class level):

    public class DefaultEnemy : MonoBehaviour
    {
        // Variables defined at the class level can 
        // be accessed from any method in the class
        int phealth = 0;
        int pdamage = 0;
        int ehealth = 0;
    
        public static void DefineVariables()
        {
            phealth = GameObject.Find("VStorage").GetComponent<VStorage>().phealth;
            pdamage = GameObject.Find("VStorage").GetComponent<VStorage>().pdamage;
            ehealth = GameObject.Find("VStorage").GetComponent<VStorage>().ehealth;
        }
    
        public static void Attack()
        {
            ehealth = ehealth - pdamage;
        }
    
        private void Start()
        {
            DefineVariables();
        }
    }