Made player and enemies into a trigger; gave them "enemy" tag; the projectile now destroys up to 2 enemies.
void OnTriggerEnter2D(Collider2D coll)
{
Debug.Log ("collided with" + coll.gameObject.name);
if (coll.gameObject.tag == "enemy")
{
Destroy (coll.gameObject);
gameControl addScore = GetComponent<gameControl>();
addScore.scoring ();
hitNum += 1;
}
if (hitNum >= 2)
{
DestroyObject(this.gameObject);
}
}
problem? addScore.scoring isn't working :(
gameControl.cs function below:
public void scoring ()
{
Debug.Log ("scoring is being called");
playerScore += 1;
}
Error, on the addScore.scoring(); line:
NullReferenceException: Object reference not set to an instance of an object
projectile_sc.OnTriggerEnter2D (UnityEngine.Collider2D coll) (at Assets/projectile_sc.cs:36)
Note:
Have the ranged minions walk around the edge of arena, shooting at the player. Maybe put in obstacles for player to hide behind.
Update:
Made score a static variable and scoring a static function.
A static function can be called without an object reference.
Scoring, in gameControl script:
public static void scoring ()
{
playerScore += 1;
Debug.Log (playerScore);
}
Calling it from another script:
gameControl.scoring ();
Had a Singleton tutorial from herbie.
It's essentially a static public class that creates an instance of itself when called, so other scripts can access the non-static functions attached to it. Should only be used when there is only 1 of it, like in scoring.
public class scores : MonoBehaviour {
protected static scores m_instance = null;
protected int m_currentScore = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public static scores instance ()
{
if ((m_instance) == null)
{
m_instance = new GameObject("scoresSingleton").AddComponent<scores>();
}
return m_instance;
}
public void increaseScore()
{
m_currentScore++;
Debug.Log (m_currentScore);
}
}
GetComponent only works on things attached to current object.
FindComponentbyType/Name are slower functions and I should avoid using these in updates.
When using either, store the results in an variable and just use those.
Use the "xxx = null" "if xxx = null, xxx = return value" to make sure xxx only gets defined once.
No comments:
Post a Comment