Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

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

    }
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...