I am making a VR game where I want to display the ammo next to the gun. I keep getting a error and dont know how to fix it. Please help
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ammoText : MonoBehaviour
{
public GameObject weapon;
Text ammoText;
void Awake()
{
ammoText = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
ammoText.text = weapon.GetComponent<Gun>().currentBullets.ToString();
}
}
CodePudding user response:
After passing line public class ammoText : MonoBehaviour
the compiler knows that ammoText
is a class and this is used to evaluate the correctness of the code. Statement Text ammoText;
generates a compilation error because class ammoText
must not occur in such a statement. Also other occurrences of ammoText
will generate errors.
It is recommended to start class names with capital letters so it may be enough to rename the class to AmmoText
.
CodePudding user response:
You can't name a variable the same as your class name. Change the text field name from ammoText
to something else.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ammoText : MonoBehaviour
{
public GameObject weapon;
Text renameThis;
void Awake()
{
renameThis = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
renameThis.text = weapon.GetComponent<Gun>().currentBullets.ToString();
}
}