Daemonique
Daemonique

Reputation: 648

Can a unity script simply be a public variable

I was trying to add a script that attaches a global damage rating to the object however the script came up with a console error,

error CS0120: An object reference is required for the non-static field, method, or property AttackStat.atk

So I am confused, is there a requirement for a unity script that I am not meeting or something, I am quite new to programming in unity

Thanks for your time

Attackstat.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttackStat : MonoBehaviour
{
    public float atk;

}

Upvotes: 1

Views: 64

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29036

Solution 1:

As the error message stated, atk is an instance member of the class AttackStat you need to create an instance/object of the class to access them.

For example :

AttackStat attackStatInstance = new AttackStat();
float  vlueObject = attackStatInstance.atk // It is accessible now 

Solution 2:

If you really want to use atk without creating the instance(say AttackStat.atk) then the variable should be defined as static, that means the definition will be like the following:

public class AttackStat : MonoBehaviour
{
    public static float atk;
}

Upvotes: 1

siusiulala
siusiulala

Reputation: 1070

The answer is YES, check Static Members

public class AttackStat : MonoBehaviour
{
    public static float atk;
}

Upvotes: 1

Related Questions