Hello,
This has completely brought my Ludum Dare weekend to a halt (booo), but I’ve tried for hours to figure out how to do this / what Unity is doing to no avail.
Basically I want to do this:
• Fire rigidbody projectile
• Projectile hits a GameObject tagged with ‘prop’ which also has a Prop.CS on it
• Inside Prop.CS are strings like ‘lookAtDescription’ (blah blah…stuff unique to that prop)
• Print the string on the UI Canvas
No matter what I did today, I couldn’t get Unity to access or show the string. At first, it looked like the issue I had was my UI text simply wouldn’t update, even though I could query the variable and text object with Print() and get the correct data. Then, with more digging around and debugging it looked like for the single frame of the collision things were getting set, but then immeditally going blank / null.
Let me show you how I set it up:
- This is what a prop in the level would have on it. Then in the inspector it has a string setup. Simple.
public class Prop : MonoBehaviour {
public string lookAtResponse;
}
- A rigidbody projectile is then instantiated from a fire script:
if (Input.GetMouseButtonDown(0))
{
switch (ammoState.activeAmmo)
{
case 1:
projectileInstance = Instantiate(LookAtProjectile, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
projectileInstance.AddForce(barrelEnd.forward * 300);
break;
case 2:
projectileInstance = Instantiate(TalkToProjectile, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
projectileInstance.AddForce(barrelEnd.forward * 300);
break;
}
}
- The projectile then has a check on it to see if it collided with a prop, and then if so, to create a reference to the prop.cs string ‘lookAtResponse’. It then passes this string through to a method on the canvas.
public class LookAtHit : MonoBehaviour {
Prop propHit;
public UIObserver uIObserver;
public void OnCollisionEnter(Collision collision)
{
//If we collide with a prop
if(collision.gameObject.tag == "Prop")
{
//Get the prop stuff
propHit = collision.gameObject.GetComponent<Prop>();
//Call method on UI Observer and pass through the prop description
uIObserver.OnPropHit(propHit.lookAtResponse);
//Destory the projectile
Destroy(gameObject);
}
}
}
- The canvas then had a method (and links) to a text element in the UI
public void OnPropHit(string lookAtText)
{
mainText.text = lookAtText;
}
No matter what I did, the text never changed. No errors. No warnings. No suggestion of any missing references…etc
If anyone has any suggestions or insight they’d be massively appreciated.
Many thanks!