Question by
saiyanslayer · Jul 19, 2017 at 03:28 PM ·
scripting beginnervariables
Unable to set String Variable in Script
I'm trying to name gameobjects with a script to easily reference a specific gameobject.
This is the script attached to the hero is contain their name:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HeroIcon : MonoBehaviour {
public int health;
public int health_max;
public Sprite icon;
public string[] qualities;
[SerializeField]
string HeroName;
public Vector3 target;
public float speed;
// Use this for initialization
void Start () {
health = health_max;
target = transform.position;
}
// Update is called once per frame
void Update () {
if (target != null) {
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target, step);
}
}
public string getHeroName() {
return HeroName;
}
public void setHeroName(string name) {
HeroName = name;
}
}
This is how I'm setting the hero gameobject in my GameManager script:
int heronumber = GameObject.FindGameObjectsWithTag("Hero").Length;
if (heronumber < 1) {
GameObject guy = Instantiate(hero) as GameObject;
guy.GetComponent<HeroIcon>().setHeroName("Dan");
}
This is how I'm trying to find the object:
if (Input.GetMouseButtonDown(0)) {
var hero = GameObject.FindGameObjectWithTag("Hero");
if (hero.GetComponent<HeroIcon>().getHeroName() == "Dan") {
hero.GetComponent<HeroIcon>().target = transform.position;
}
}
The object is created, but doesn't have a HeroName. Am I doing something wrong, or is there something preventing that variable from being set?
Comment