GUIText Instantiation and Update the Instantiated Text. C#

Hello,

What I am trying to do is instantiate the damage you do on an enemy and render the damage you did on the text that is instantiated. Here is the script I am working on. I have tried multiple methods that I thought might work, but thus far no success. Unity Answer folk to the rescue?

private GUIText GUIDamage;
public GameObject GUIPrefab;

void Damage ( float damage  ){
  	GameObject GUIDamage = Instantiate(GUIPrefab, Camera.main.WorldToViewportPoint(gameObject.transform.position), Quaternion.identity);
    GUIDamage.guiText = Shooting.damageToSend;
    }

Currently I have gotten various errors with various methods of trying to get it to work. I have seen a similar script on Unity Answers about this, but it was in that nasty Unityscript. :open_mouth:

The current error I recieve is : " Cannot implicitly convert type UnityEngine.Object' to UnityEngine.GameObject’. An explicit conversion exists (are you missing a cast?)" I think I know why I get this, I just don’t know how to get the code to work without errors haha.

Cheers, Thank you for your time.

The problem is that you are trying to define GUIDamage twice, as different types!

First, here-

private GUIText GUIDamage;

then, here-

GameObject GUIDamage

Not only will this cause issues with one hiding the other, I doubt that that is actually what you want.

In this case, you should stop trying to re-define GUIDamage. It’s defined correctly the first time, there’s no need to define it again (and it would disappear at the end of the scope if you did anyway).

Instead, use GetComponent to grab the GUIText out of the newly instantiate object, and then you can refer to GUIDamage in Update to modify the text!

GUIDamage = ((GameObject)Instantiate(GUIPrefab, Camera.main.WorldToViewportPoint(gameObject.transform.position), Quaternion.identity)).GetComponent<GUIText>();