简体   繁体   中英

Referencing a non static member with an instantiated object

I want this class to render a grid each time it is instantiated, but I am getting the error, error

CS0120: An object reference is required to access non-static member `UnityEngine.GameObject.GetComponent(System.Type)'

So I instantiate an object of Renderer called Rend and set that equal to the non-static member but I am still getting the error? Any help would be greatly appreciated as I have researched for several hours and still can't figure this out.

using UnityEngine;
using System.Collections;

public class SetGrid : MonoBehaviour {

    public int x = 1;
    public int y = 1;

    void Start()
    {
        Renderer Rend = GameObject.GetComponent<Renderer>().material.mainTextureScale = new Vector2 (x, y);

    }
}

I am assuming this script is part of your grid game object which also has a component of type Renderer .

The correct syntax to scale the texture of the Renderer is following:

public class SetGrid : MonoBehaviour {

    public int x = 1;
    public int y = 1;

    void Start()
    {
        // Get a reference to the Renderer component of the game object.
        Renderer rend = GetComponent<Renderer>();
        // Scale the texture.
        rend.material.mainTextureScale = new Vector2 (x, y);
    }
}

The error message was thrown because you tried to call GetComponent on a type of GameObject and not an instance of GameObject . The script itself is already in the context of a GameObject meaning that you can just access a component with GetComponent from a non-static method.

The problem is not with the Rend object, it's caused by the fact that the GetComponent method is non-static. That means you need to instantiate a GameObject object and use that one to call GetComponent.

Change GameObject.GetComponent to gameObject.GetComponent , so that you're referencing the gameObject that this MonoBehaviour script belongs to.

Or you can even not use gameObject.GetComponent and just use GetComponent by itself.

See the MonoBehaviour inherited members for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM