Reputation: 9
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);
}
}
Upvotes: 0
Views: 112
Reputation: 6169
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.
Upvotes: 0
Reputation: 3573
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.
Upvotes: 1
Reputation: 1770
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.
Upvotes: 0