简体   繁体   中英

UNity3D error displaying variable from another script c#

I got a UI Text element (inside a canvas) that I need to grab a value from another script.

The way I'm doing right now (and that was the closest I got to get it working) is:

public class AttributeValueController : MonoBehaviour {

//public AttributeName attribute;
[SerializeField]
private Text attributeValue = null;

// Use this for initialization
void Start () {
    attributeValue.text = CharacterGenerator._toon.GetPrimaryAttribute("Might").AdjustedBaseValue.ToString();   
}

I got the text component I want to be changed set on on the inspector to the "attributeValue".

When I run this I get the errors

Assets/Scripts/HUD Classes/AttributeValueController.cs(19,58): error CS0120: An object reference is required to access non-static member `CharacterGenerator._toon'

and

NullReferenceException: Object reference not set to an instance of an object UnityEngine.UI.Graphic.OnRebuildRequested () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Graphic.cs:480) UnityEngine.UI.GraphicRebuildTracker.OnRebuildRequested () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/GraphicRebuildTracker.cs:33) UnityEngine.CanvasRenderer.RequestRefresh () (at C:/buildslave/unity/build/artifacts/generated/common/modules/UI/CanvasRendererBindings.gen.cs:314)

Anyone can help? When I replace this function by "0" it works... I've searched everywhere and I cannot fix it

If CharacterGenerator isn't a static class, you can't access it like that. You would have to make an instance of the class to access properties.

CharacterGenerator cGen = new CharacterGenerator();
attributeValue.text = cGen._toon.GetPrimaryAttribute("Might").AdjustedBaseValue.ToString();

Although, given this is a new instance of the class, I would not expect these properties to be populated, but perhaps your class is structured so that they are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM