- Home /
How to reference the current colliding object's script
I am working on a project that simulates the Pathfinder RPG Hex Exploration and Kingdom Building rules.
I have a project with a scene that generates a 7×11 hex grid, using an instance of prefabColider which has attached to it the HexDetails script, and at runtime assigns instanced geometry from a series of prefabs.
The HexDetails script keeps a track of the type of terrain and features the hex has, as well as it has been explored or not (all Booleans).
I have a First Person Controller with a Daytime script attached which keeps track of how many hours have passed and events.
I can successfully run the scene, generating the prefab colliders and the basic terrain.
When I move my first person controller from hex to hex, the script in HexDetails onTriggerEnter fires off fine on the colliders, allowing me to track the travel time from one hex to the next.
However, I have assigned a function called ExploreHex (found in the Daytime script on the First Person Controller) which I want to detect whether or not the current prefabCollider the First Person Controller is colliding with (a prefabCollider(Clone) instance) has been explored (the instanced HexDetails script's Explored Boolean switches to true), and if not, set the Explored Boolean to true. The script to increment the time passed works, but then the console throws out an error:
NullReferenceException: Object reference not set to an instance of an object Daytime.ExploreHex () (at Assets/Imported Assets/Scripts/Daytime.cs:58) Daytime.Update () (at Assets/Imported Assets/Scripts/Daytime.cs:50)
I can only assign individual prefabCollider(Clone) instances to the Daytime script on my First Person Controller, but I need it to be looking at the current instanced HexDetails on the collider prefab it is currently touching, not on a particular oneā¦
Please help?
using UnityEngine;
using System.Collections;
public class Daytime : MonoBehaviour
{
public Light sunLight;
public int timeofDay = 0;
public int periodofDay = 0;
public Texture2D[] hudTimeofDay;
public GUITexture timeAmountHUDGUI;
public int timePassed = 0;
public int daysPassed = 0;
public int hoursPassed = 0;
private string timePassedMessage = "";
private string currentPeriodofDay ="";
public int plainsHexTravelTime = 5;
public int otherHexTravelTime = 8;
public HexDetails getHexDetails;
// Use this for initialization
void Start ()
{
timePassed = 0;
timeofDay = 0;
periodofDay = 0;
sunLight = GameObject.Find("Sun").GetComponent<Light>();
sunLight.transform.eulerAngles = new Vector3 (-90, 0, 0);
}
// Update is called once per frame
void Update ()
{
if (Input.GetButtonDown ("Rest"))
{
Rest ();
}
if (Input.GetButtonDown ("Inventory"))
{
//Rest ();
}
if (Input.GetButtonDown ("Tarry"))
{
Tarry ();
}
if (Input.GetButtonDown ("Explore"))
{
ExploreHex ();
}
}
public void ExploreHex()
{
//Determine time passed from exploring
if (getHexDetails.Explored ==false)
{
timePassed = timePassed + 24;
//Calculate time passed and period of day
daysPassed = (timePassed / 24);
hoursPassed = timePassed - (daysPassed * 24);
whatPeriodofDay ();
//Set hex to Explored
//GameObject go = GameObject.FindObjectOfType ("prefabCollider(Clone)");
getHexDetails = FindObjectOfType(typeof(HexDetails)) as HexDetails;
getHexDetails.HexExplored();
}
else
{
Debug.Log ("The Hex has already been Explored");
}
}
public void Rest()
{
//Determine time passed from resting
timePassed = timePassed + 8;
//Calculate time passed and period of day
daysPassed = (timePassed / 24);
hoursPassed = timePassed - (daysPassed * 24);
whatPeriodofDay ();
}
public void Tarry()
{
//Determine time passed from waiting
timePassed = timePassed + 1;
//Calculate time passed and period of day
daysPassed = (timePassed / 24);
hoursPassed = timePassed - (daysPassed * 24);
whatPeriodofDay ();
}
public void EnterOtherHex()
{
//Determine time passed from travel
timePassed = timePassed + otherHexTravelTime;
//Calculate time passed and period of day
daysPassed = (timePassed / 24);
hoursPassed = timePassed - (daysPassed * 24);
whatPeriodofDay ();
}
public void EnterHex()
{
//Determine time passed from travel
timePassed = timePassed + plainsHexTravelTime;
//Calculate time passed and period of day
daysPassed = (timePassed / 24);
hoursPassed = timePassed - (daysPassed * 24);
whatPeriodofDay ();
}
public void whatPeriodofDay()
{
// Get the time of day
timeofDay = (hoursPassed);
// Figure out what time of day it should be and change the time indicator. Also, set the angle of the Sun.
switch (timeofDay)
{
case 0:
{
periodofDay = 0; //Difines the period of day
currentPeriodofDay = "midnight"; //Name of period of day
sunLight.light.transform.eulerAngles = new Vector3(-90,0,0); //Sets sun angle for period
sunLight.light.intensity = 0.2f; //Sets sun intensity for the period
break;
}
case 1:
case 2:
case 3:
case 4:
case 5:
{
periodofDay = 1;
currentPeriodofDay = "night";
sunLight.light.transform.eulerAngles = new Vector3(-90,0,0);
sunLight.light.intensity = 0.2f;
break;
}
case 6:
{
periodofDay = 2;
currentPeriodofDay = "dawn";
sunLight.light.transform.eulerAngles = new Vector3(0,0,0);
sunLight.light.intensity = 0.5f;
break;
}
case 7:
case 8:
case 9:
case 10:
case 11:
{
periodofDay = 3;
currentPeriodofDay = "morning";
sunLight.light.transform.eulerAngles = new Vector3(45,0,0);
sunLight.light.intensity = 0.9f;
break;
}
case 12:
{
periodofDay = 4;
currentPeriodofDay = "midday";
sunLight.light.transform.eulerAngles = new Vector3(90,0,0);
sunLight.light.intensity = 1.2f;
break;
}
case 13:
case 14:
case 15:
case 16:
case 17:
{
periodofDay = 5;
currentPeriodofDay = "afternoon";
sunLight.light.transform.eulerAngles = new Vector3(135,0,0);
sunLight.light.intensity = 0.9f;
break;
}
case 18:
{
periodofDay = 6;
currentPeriodofDay = "dusk";
sunLight.light.transform.eulerAngles = new Vector3(180,0,0);
sunLight.light.intensity = 0.5f;
break;
}
case 19:
case 20:
case 21:
case 22:
case 23:
{
periodofDay = 7;
currentPeriodofDay = "evening";
sunLight.light.transform.eulerAngles = new Vector3(-90,0,0);
sunLight.light.intensity = 0.2f;
break;
}
}
// Update HUD with current time period
timeAmountHUDGUI.texture = hudTimeofDay[periodofDay];
// Prints feedback to the console for debugging
timePassedMessage = daysPassed + " days and " + hoursPassed + " hours have passed since the start of the adventure. It is currently period #" + periodofDay + " at " + timeofDay + " hours and " + currentPeriodofDay;
Debug.Log (timePassedMessage);
//timeofDay++;
//timeAmountHUDGUI.texture = hudTimeofDay[timeofDay];
}
}
using UnityEngine;
using System.Collections;
//[ExecuteInEditMode]
public class HexDetails : MonoBehaviour
{
// ====================================================================================================================
#region Hex Type
[SerializeField]
//Sets type of hex
public bool PlainsHex;
public bool ForestHex;
public bool HillsHex;
public bool MountainHex;
public bool DesertHex;
public bool MarshHex;
#endregion
// ====================================================================================================================
#region Natural Feature
//Sets natural features of the hex
[SerializeField]
public bool RiverHex;
public bool ResourceHex;
public bool PlantHex;
public bool DeadBodyHex;
public bool LandmarkHex;
public bool RuinHex;
public bool MonsterHex;
public bool LairHex;
public bool HutHex;
public bool TrapHex;
public bool CampHex;
public bool StructureHex;
public bool SettlementHex;
#endregion
// ====================================================================================================================
#region Kingdom Building Improvements
//Sets Kingdom Building Hex modifiers
public bool AqueductHex;
public bool BridgeHex;
public bool CanalHex;
public bool FarmHex;
public bool FisheryHex;
public bool FortHex;
public bool HighwayHex;
public bool MineHex;
public bool QuarryHex;
public bool RoadHex;
public bool SawmillHex;
public bool Watchtower;
#endregion
// ====================================================================================================================
#region inspector properties
//Set whether or not the hex is already explored
public bool Explored;
#endregion
// ====================================================================================================================
#region Travel Time
public int TravelTime;
#endregion
// ====================================================================================================================
#region Prefab Assignments
//initialise list of prefabs to be generated
public GameObject prefabPlainsHexprefab;
public GameObject prefabHillsHexprefab;
public GameObject prefabForestHexprefab;
public GameObject prefabMountainHexprefab;
public GameObject prefabTradingPostprefab;
#endregion
// ====================================================================================================================
#region Prefab active checks
//Initialise checks for tile Generation
public int isPlains;
public int isHills;
public int isForest;
public int isMountain;
public int isFort;
#endregion
// Use this for initialization
void Start ()
{
TravelTime = 0;
GenerateChecks ();
GenerateHexTiles ();
}
// Update is called once per frame
void Update ()
{
}
public void GenerateChecks()
{
isPlains = 0;
isHills = 0;
isForest = 0;
isMountain = 0;
isFort = 0;
}
public void GenerateHexTiles()
{
if (PlainsHex == true)
{
if (isPlains == 0)
{
//Instantiate prefab now
var temp = Instantiate(prefabPlainsHexprefab, transform.position, Quaternion.identity) as GameObject;
temp.transform.parent=transform;
isPlains = 1;
}
}
if (HillsHex == true)
{
if (isHills == 0)
{
//Instantiate prefab now
var temp = Instantiate(prefabHillsHexprefab, transform.position, Quaternion.identity) as GameObject;
temp.transform.parent=transform;
isHills = 1;
}
}
if (ForestHex == true)
{
if (isForest == 0)
{
//Instantiate prefab now
var temp = Instantiate(prefabForestHexprefab, transform.position, Quaternion.identity) as GameObject;
temp.transform.parent=transform;
isForest = 1;
}
}
if (MountainHex == true)
{
if (isMountain == 0)
{
//Instantiate prefab now
var temp = Instantiate(prefabMountainHexprefab, transform.position, Quaternion.identity) as GameObject;
temp.transform.parent=transform;
isMountain = 1;
}
}
if (FortHex == true)
{
if (isFort == 0)
{
//Instantiate prefab now
var temp = Instantiate(prefabTradingPostprefab, transform.position, Quaternion.identity) as GameObject;
temp.transform.parent=transform;
isFort = 1;
}
}
}
void OnTriggerEnter(Collider player)
{
if (PlainsHex)
{
player.gameObject.SendMessage("EnterHex");
}
else
{
player.gameObject.SendMessage("EnterOtherHex");
}
}
public void HexExplored()
{
//Set hex to Explored
Explored = true;
}
}
Answer by vargata · Dec 31, 2013 at 03:30 PM
I didn't go further but the error is caused by not initializing the Hexdetails object...
public HexDetails getHexDetails = new HexDetails();
Thanks for the reply vargata, I replaced:
public HexDetails getHexDetails;
...with your code in Daytime.cs. However, I got an error:
You are trying to create a $$anonymous$$onoBehaviour using the 'new' keyword. This is not allowed. $$anonymous$$onoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
Any ideas?
The individual scripts on the cloned objects are not updating when x (mapped to ExploreHex()) is pressed, and the Debug.Log text stating that the Hex has been explored appears on the second try, even in another Hex...
Actually, looking at it, I am not sure that my colliders are prefabs, they are black in the Hierarchy... If this is weird, the problem could be in the Hex$$anonymous$$anager script...
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Object reference not set to an instance of an object 1 Answer
Object Reference Not Set to an Instance of an object 0 Answers
Targetting Script Error Help 1 Answer
Can't reference Camera in Prefab 1 Answer