-2

I am making a simple game in Unity2D and even after numerous tries, CS0120 error still occurs.

I have been already looking thru some tutorials/help but none of them really helped me and I dont wanna mess up my code even more.

//This is the one which I want to call the var from
public class Terraform : MonoBehaviour
{
    public int TerraformClick;

    void Start()
    {        
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(1))
        {
            TerraformClick = 1;
        }
    }
}

//And this is the main script
public class Grass_Follow : MonoBehaviour
{    
    void Awake()
    {
        GameObject TerraformButt = GameObject.Find("Terraform");
        Terraform terraformScript = TerraformButt.GetComponent<Terraform>();  //finding the object            
    }

    void Update()
    {
        //probably some mistake in calling the variable
        if (Terraform.TerraformClick == 1)
        {
            Vector3 pz = 
                Camera.main.ScreenToWorldPoint(Input.mousePosition);
            pz.z = 0;
            transform.position = pz;
        }
        else
        {                    
        }                
    }   
}

I expect just some small mistake with the variable placement/calling

Sean Carey
  • 799
  • 5
  • 12
Waterpig
  • 3
  • 1
  • `Terraform.TerraformClick` -> `TerraformClick`. It's a non-`static` member variable – UnholySheep Feb 16 '19 at 20:46
  • 4
    Before taking potshots at arbitrarily trying anything further, make an effort to understand **what** the error CS0120 and its error message exactly tell you about what is wrong with precisely **which code line(s)**... –  Feb 16 '19 at 20:48
  • 4
    It also helps to tell us **the entire compiler error message**, not just the ID. – mjwills Feb 16 '19 at 20:52

1 Answers1

0

You were on the right track. It's just that you have to declare 'terraformScript' outside of the Awake function. You can still initialize it inside the Awake function, but it should be declared outside of that function. This is because you don't just want that variable to only exist inside the Awake function, do you? No. You also want your Update function to have access to it as well. So just declare it at the top of your script, so that all of your functions can have access to it as well. We call these variables member variables.

using UnityEngine;

public class Grass_Follow : MonoBehaviour
{        
    Terraform terraformScript; 

    void Awake()
    {
        GameObject TerraformButt = GameObject.Find("Terraform");
        terraformScript = TerraformButt.GetComponent<Terraform>();
    }

    void Update()
    {
        if (terraformScript.TerraformClick == 1)
        {
            Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            transform.position = pz;
        }
    }
}
Sean Carey
  • 799
  • 5
  • 12