bryleinandan / MPGD-Main-Game

2 stars 0 forks source link

StackOverflow when trying to set prompt text #16

Open jrufus09 opened 2 days ago

jrufus09 commented 2 days ago

Interaction system requires

A new feature was added to produce a text prompt above an object when in range. Collision, detection and adding to inventory work as intended (destruction of object not yet tested).

The feature uses a TextMeshProUGUI.

image

This happens when interacting with the object.

For further clarification, the interface defines that there should be a textmeshprougui in any child that inherits from it; there requires definition of a getter and setter within every child class --- therein the issue lies. It's recursively trying to set the text for some reason

I've probably just not set up canvases right or something

jrufus09 commented 1 day ago

ChatGPT says:

In the getter, you're trying to return promptTextMesh, which actually calls the getter itself. In the setter, you're assigning a value to promptTextMesh, which calls the setter itself. This creates an infinite loop for both the getter and setter.

How to Fix It You need to use a backing field to store the actual value of promptTextMesh. Here's the corrected version:

// Private backing field
private TextMeshProUGUI _promptTextMesh;

public TextMeshProUGUI promptTextMesh
{
    get { return _promptTextMesh; }
    set { _promptTextMesh = value; }
}

Explanation _promptTextMesh is a private field that actually holds the reference to your TextMeshPro object. The getter returns _promptTextMesh. The setter assigns the incoming value to _promptTextMesh. Alternative: Auto-Implemented Property If you don't need any custom logic in the getter or setter, you can use an auto-implemented property: public TextMeshProUGUI promptTextMesh { get; set; } This is equivalent to the corrected version above but is more concise. Unity will automatically handle the backing field for you.

jrufus09 commented 1 day ago

That's cool. Automatic getter and setter worked. I don't remember why I tried to make them manually, since get; set; are all defined in the interface

Now have a nullreference exception telling me that the textmeshprompt doesn't exist :D

jrufus09 commented 1 day ago

It's because i've been referencing textmeshproUGUI and i think this only exists as a component. as an object, it's called a TextMeshPro. so the object is found just fine now. but the text doesn't display :)