- Home /
Change the text of GameObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Interactable : MonoBehaviour
{
public GameObject InteractionPanel;
public Text InteractionText;
private bool isAllowed;
void Update()
{
if (isAllowed && Input.GetKey(KeyCode.E))
{
Debug.Log("I'm interacting!");
}
}
public virtual void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
Debug.Log("I'm came in interacting area");
InteractionPanel.SetActive(true);
isAllowed = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
Debug.Log("I'm quit interacting area");
InteractionPanel.SetActive(false);
isAllowed = false;
}
}
}
So, i have a class for all Interactable objects. It's very simple. Just showing up the text on top, when player able to interact with it. The problem which i meet, it's.. I have kinda 2 types on Interactable Objects - NPC and Items, so i created to another classes for them. So, i want to change the text inside the InteractionText, which depends on object I interact with. Basically, when i interact with the item it's should show the "press E to pickup" or if it's the NPC show "press E to talk"
public class NPC : Interactable
{
public override void OnTriggerEnter2D(Collider2D collision)
{
InteractionText.text = "press E to talk";
base.OnTriggerEnter2D(collision);
}
}
public class Item : Interactable
{
public override void OnTriggerEnter2D(Collider2D collision)
{
InteractionText.text = "press E to pickup";
base.OnTriggerEnter2D(collision);
}
}
I made it like this. Maybe some review, advices?
Your answer
Follow this Question
Related Questions
Change Text of GUI Button from Script 2 Answers
What is wrong with my text changing script? 1 Answer
Is it possible to make a text with different font families? 3 Answers
Lags, when i clicked several time on button 1 Answer
Clicking a button will display that buttons text in a seperate text-field 1 Answer