SpunkTrumpet
SpunkTrumpet

Reputation: 131

Required to access non-static member

I'm trying to call a function from one script into another but I'm getting: An object reference is required to access non-static member FireBlock.FireOn()

The script with the function I am trying to call is FireBlock containing this which is attached to a box collider attached to a game object.

using UnityEngine;
using System.Collections;

public class FireBlock : MonoBehaviour {
public void FireOn ()
{
    collider.enabled=false;
}

Here's how I'm trying to call it in the other script.

void Update ()
{

    FireBlock.FireOn ();
}

Any ideas where I'm going wrong? I've tried making the FireOn function public static, just void but nothings working.

Upvotes: 1

Views: 5395

Answers (2)

Burdock
Burdock

Reputation: 1105

Assuming you are trying to access a mono behavior, you first need to access the GameObject..

There are a few ways to do this, here are your main tools.

GameObject.Find(name string) 



GameObject.FindWithTag(tag string) 

Once you have your gameobject, now you need to get the script. You do this with GetComponent<>()

All together it looks like this '

FireBlock MyFireBlock = GameObject.Find("mygameobject").GetComponent<FireBlock>() ;

Or

GameObject mygameobject = GameObject.Find("mygameobject") ; 


FireBlock MyFireBlock  = Mygameobject.GetComponent <FireBlock>();

`

Upvotes: 1

Habib
Habib

Reputation: 223237

You need to create instance of FireBlock and then call the method with that instance.

FireBlock fireBlock = new FireBlock();
fireBlock.FireOn();

Since FireOn is an instance method you can't call it with the class name. You can only do that for static methods.

Upvotes: 4

Related Questions