I refer the website for proper way of referencing the script How to call a public function from another script in Unity? but it does not work, still return a nullreference exception in the example below. Not sure how to fix it.Apart from that I also consider using
int a;
public int A
{ get; set; }
and in HPscript using spawnpoint.A = spawnpoint.A - 1; but it come out the content is for read only.
Below is the codes I using.
I attach this code to a capsule gameobject that is use to spawn prefab gameobject,drag and drop prefab to the enemy GameObject inspector window, this part working correctly.
using System;
using UnityEngine;
public class Spawnpoint: MonoBehaviour
{ public GameObject Enemy;
public int a;
int currentstate = 0;
int previousstate = 0;
void Counting()
{//the below if statement is to ensure the Gameobject only spawn once when condition become true
//in every 10seconds
var d = DateTime.Now.Second % 10;
if(d==0)
{
currentstate = 1;
}
else
{
currentstate = 0;
}
}
void Spawn()
{//Stop spawning when Gameobject equal 5
if (d==0&¤tstate!=previousstate)
if(a<5)
{
Instantiate(Enemy, new Vector3(UnityEngine.Random.Range(0, 4), 1, UnityEngine.Random.Range(0, 4)),Quaternion.identity);
a = a+1;
}
}
void Update()
{
Counting();
Spawn();
previousstate = currentstate;
}
}
The script below is not working. I want the HPscript to deduct the value "a",in Spawnpoint script so the script will continue spawn enemy when number less than 5.This script is attached to the prefab gameobject that is place in asset folder.
using System;
using UnityEngine;
public class HPScript : MonoBehaviour
{ Spawnpoint spawnpoint;
void Start()
{
spawnpoint = GetComponent<Spawnpoint>();
}
public void counting()
{
var c = DateTime.Now.Second % 30;
if(c==0)
{
spawnpoint.a = spawnpoint.a - 1;
Destroy(gameObject); }
}
void Update()
{
counting();
}
}
Gameobject.Find("YourSpawnerName")
. The alive time of your HP script is as well not always the same with your % 30, better use an Invoke("DestroyFunction", 30f) \$\endgroup\$