how to access functions of one scripts in another script in unity?

Updated on April 19, 2017 in Unity
Share on Facebook0Tweet about this on Twitter0Share on Google+0Share on Reddit0
1 on April 17, 2017

I am using PlayerHealth script in EnemyAI scripts but it is not working the error in the console is ” NullReferenceExpection: object reference not set to an instance of an object ” thank you

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealth : MonoBehaviour {
public GameObject enemy;
public int player_Health =90;
public int playerDamagedHealth = 30;
public bool isDead =false;
public void PlayerDamage(){
if (player_Health > 0)
{
player_Health = player_Health - playerDamagedHealth;
if (player_Health <= 0) {
//isDead = true;
player_Health = 0;
print ("game over");
}
print (player_Health);
}
}
public void PlayerHealthRecovery(){
if (player_Health != 0 && !isDead) {
player_Health =+ 5;
print (player_Health);
}
}
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAI : MonoBehaviour {
public float Distance;
public Transform Player,Hostage;
public float chaseRange = 15.0f;
public float Damping = 6.0f;
private CharacterController controller;
public float gravity = 20.0f;
bool Entered = false;
Animator anim;
public static PlayerHealth playerHealth;
Player_Shooting player_Shooting;
void Start()
{
Player = GameObject.FindGameObjectWithTag("Player").transform;
anim = GetComponent ();
playerHealth = GetComponent ();
player_Shooting = GetComponent ();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player") {
print ("entered");
Entered = true;
anim.SetBool ("Attack", Entered);
 playerHealth.PlayerDamage ();
}
}
void OnTriggerExit(Collider other) {
if (other.gameObject.tag == "Player") {
Entered = false;
anim.SetBool ("Attack", Entered);
 playerHealth.PlayerHealthRecovery ();
}
}
public void EnemyDead()
{
}
}
  • Liked by
Reply
0 on April 19, 2017

You have to reference the script component on the gameobject the script is attached to.

  • Liked by
Reply
Cancel