I’m fairly new to coding so please don’t murder me if this is a pretty basic answer. I tried doing this in c# as shown below.
using UnityEngine;
using System.Collections;
public class mesagebox : MonoBehaviour {
void OnGUI (){
if(transform.position.x <20){
GUI.Box(new Rect(50,50, 500, 500), "Text Area");
}
}
}
I couldn’t get it to work. I’m trying to get a message box appear when my player is near the cube. I figured i needed to put in a box collider and trigger it. but it didn’t work. I figured i might need to tag the player in some way to trigger it, I spent the better part of an hour looking through google and such for an answer. The only resources i could find, including unity scripting reference was all java script.
The Unity Scripting reference is in both Javascript and C#. To the top-right of each code box you should have a drop down menu that let’s you switch between the two.
I’d say, take a different approach. Using OnTrigger funtions you could let the physics-engine handle it. Similar to this, script on cube approach:
You will need 2 objects. PlayerObject, give this RigidBody and Collider. Cube, give this Collider and set IsTrigger to true (you will find this in the “inspector view”). Set one of these colliders radius or range to the distance you need. (I’d say, preferably the collider on the Cube)
use this script on the Cube
using UnityEngine;
using System.Collections;
public class CubeHandler : MonoBehaviour
{
void OnTriggerEnter(Collider target)
{
if( target.name == PlayerObject ) {/*GUICODE*/}
}
}
start by testing using Debug and checking the console.
Debug.Log("StringMessage");
I believe it to be possible to swap the handling script, rigidbody, and IsTrigger for a “reversed” way to handle it. (I would suggest that the player should keep a rigidbody if you try this)
using UnityEngine;
using System.Collections;
public class scriptMono : MonoBehaviour {
public Transform other;
void Update() {
if (other) {
float dist = Vector3.Distance(other.position, transform.position);
print ("Distance to other: " + dist);
if(dist < 5 ){Debug.Log ("Player is close, render box now");}
}
}
}
Really simple script, i tested it, if your player is near the cube it will print that message, just modify it calling your GUI function and we´re done. Hope it helps!