Paradizigmania
Paradizigmania

Reputation: 81

CS0120 Cant set layer mask from different script

I'm making a game where i want to change which objects my player can collide with by changing the layer mask, but every time I try to change the variable in a different script it throws this error

Error CS0120: An object reference is required to access non-static member `RaycastController.jumpableCollisionMask'

The code for where i create the variable:

 using UnityEngine;
using System.Collections;

[RequireComponent (typeof (BoxCollider2D))]
public class RaycastController : MonoBehaviour {

    public LayerMask collisionMask;

    public LayerMask jumpableCollisionMask;

The code for where i set the variable

using UnityEngine;
using System.Collections;

public class PlayerChanger : MonoBehaviour {

    public float numberOfPlayersPerLevel;


    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown (KeyCode.E)){
            RaycastController.jumpableCollisionMask = 11;
        }
    }
}

I have tried using a setter but i couldn't get it to work. Thanks in advance and have a nice day =).

Upvotes: 1

Views: 804

Answers (1)

Fattie
Fattie

Reputation: 12631

jumpableCollisionMask = 11

not

RaycastController.jumpableCollisionMask = 11

Note that you likely have another problem:

You set layer masks (which are just int) like this:

int layerMaskDogs = 1 << LayerMask.NameToLayer("Dogs");
int layerMaskFruits = 1 << LayerMask.NameToLayer("Fruits");

ok?

Never use "= 11" or any number or other value. In Unity it is now only possible to use the form 1<<LayerMask.NameToLayer("Blah")


Finally note you are using public to declare the LayerMask. That can be a bit confusing -- you only do that if you want to set it in the editor. If that's what you want to do, fine. But if you don't need to do that, just use private.


Finally note that you have this is TWO DIFFERENT SCRIPTS!!! This is the most basic problem in Unity. Fortunately it is easily solved:

-- add a public variable to your SECOND script

public class PlayerChanger : MonoBehaviour {
  public RaycastController myRC;

-- IN THE INSPECTOR take your "RaycastController" and drag it to that public variable

-- Now use it like this

public class PlayerChanger : MonoBehaviour {
     public RaycastController myRC;
     ...
     ...
     ...
     //whenever you need to use it...
     myRC.jumpableCollisionMask = 11;

Please read the literally 1000s of QA on this! Example, How to access a variable from another script in another gameobject through GetComponent?

Upvotes: 2

Related Questions