Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
202 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...