用实例化对象引用非静态成员 [英] Referencing a non static member with an instantiated object

查看:109
本文介绍了用实例化对象引用非静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望此类在每次实例化时都呈现一个网格,但是我遇到了错误,错误

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

CS0120:访问非静态成员需要对象引用 `UnityEngine.GameObject.GetComponent(System.Type)'

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

因此,我实例化了一个名为Rend的Renderer对象,并将其设置为等于非静态成员,但是仍然出现错误?我已经研究了几个小时,仍然无法弄清任何帮助,我们将不胜感激.

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

    }
}

推荐答案

我假设此脚本是您的网格游戏对象的一部分,该对象也具有类型为Renderer的组件.

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

缩放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);
    }
}


引发此错误消息是因为您尝试使用GameObject类型而不是GameObject实例调用GetComponent.该脚本本身已经在GameObject的上下文中,这意味着您可以通过非静态方法使用GetComponent访问组件.


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.

这篇关于用实例化对象引用非静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆