Home > Software design >  Using Tag to define transform for Material.SetVector
Using Tag to define transform for Material.SetVector

Time:12-16

I have a shadergraph where I pass position of gameobject as a value. Below is the code I tried for that but I get NullReferenceException.

public Material m;
private Transform player;
private GameObject character = GameObject.FindWithTag("Character");

void MoveGrass()
{
    player = character.transform;
    m.SetVector("_PlayerPosition", player.position);
}

private void OnDrawGizmos()
{
    MoveGrass();
}

private void Update() 
{
    MoveGrass();
}

Please, help me figure this out. I'm trying to make gameObjects interact with grass elements in the game, which I'm able to when I'm using Transform.position as value, but I want to make it happen using a Tag name of gameobjects to make it easier to use.

CodePudding user response:

You should use Gameobject.find in a start/awake function and recheck if it's null :

 public Material m;
    private Transform player; 
    private GameObject character;

    void Start()
    {
        character = GameObject.FindWithTag("Character");
    }

    void MoveGrass()
    {
        if (character!=null)    
        {         
            player = character.transform; 
            m.SetVector("_PlayerPosition", player.position);
        }
        else
        {
            character = GameObject.FindWithTag("Character");
        }
    }

    private void OnDrawGizmos()
    {
        MoveGrass();
        
    }

    private void Update()
    {
        MoveGrass();
    }

(I suggest you get rid of player transform and use character transform directly):

public Material m;
private GameObject character;
    
void Start()
{
    character = GameObject.FindWithTag("Character");
}
    
void MoveGrass()
{
    if (character!=null)
    {
        m.SetVector("_PlayerPosition", character.transform.position);
    }
    else
    {
        character = GameObject.FindWithTag("Character"); 
    }
    
}
    
private void OnDrawGizmos()
{
    MoveGrass();
}
    
private void Update() 
{
    MoveGrass();
}
  • Related