- Home /
(C# and Java)Unable to give the Damage from enemy bullet script to Player Health.
I want to give the Damage from enemy`s bullet script to Player Health, but it showed me this error :
Assets/Tactical Shooter AI/Tactical AI/Csharp/Damage Scripts/BulletScript.cs(15,3): error CS0246: The type or namespace name
HealthingScript' could not be found. Are you missing an assembly reference? Here is my Enemy
s bullet script the problem is in IEnumertor ApplyDamage method :
using UnityEngine;
using System.Collections;
/*
* Moves an object until it hits a target, at which time it calls the Damage(float) method on all scripts on the hit object
* Can also home in on targets and "detonate" when in close proximity.
* */
namespace TacticalAI
{
public class BulletScript : MonoBehaviour
{
public string damageMethodName = "Damage";
HealthingScript hs;
public float speed = 1000;
public LayerMask layerMask;
public float maxLifeTime = 3;
//Bullet Stuff
public float damage = 16;
//use for shotguns
public float bulletForce = 100;
public int points = 12;
//Hit Effects
public GameObject hitEffect;
public float hitEffectDestroyTime = 1;
public string hitEffectTag = "HitBox";
public GameObject missEffect;
public float missEffectDestroyTime = 1;
public float timeToDestroyAfterHitting = 0.5f;
private RaycastHit hit;
private Transform myTransform;
//Rotation
private Quaternion targetRotation;
private Transform target = null;
public float homingTrackingSpeed = 3;
public float minDistToDetonate = 0.5f;
private float minDistToDetonateSqr;
public string friendlyTag;
void Awake()
{
myTransform = transform;
Move();
StartCoroutine(SetTimeToDestroy());
}
//Automatically destroy the bullet after a certain amount of time
//Especially useful for missiles, which may end up flying endless circles around their target,
//long after the appropriate sound effects have ended.
IEnumerator SetTimeToDestroy()
{
yield return new WaitForSeconds(maxLifeTime);
if (target)
{
Instantiate(hitEffect, myTransform.position, myTransform.rotation);
}
Destroy(gameObject);
}
IEnumerator ApplyDamage()
{
//Reduce the enemy's health
//Does NOT travel up the heirarchy.
if (hit.collider.tag == "Player") {
hit.collider.SendMessage ("PlayerDamage", damage, SendMessageOptions.DontRequireReceiver);
}
//Produce the appropriate special effect
if (hit.transform.tag == hitEffectTag && hitEffect)
{
GameObject currentHitEffect = (GameObject)(Instantiate(hitEffect, hit.point, myTransform.rotation));
GameObject.Destroy(currentHitEffect, hitEffectDestroyTime);
}
else if (missEffect)
{
GameObject currentMissEffect = (GameObject)(Instantiate(missEffect, hit.point + hit.normal * 0.01f, Quaternion.LookRotation(hit.normal)));
GameObject.Destroy(currentMissEffect, missEffectDestroyTime);
}
this.enabled = false;
yield return null;
//Wait a fram to apply forces as we need to make sure the thing is dead
if (hit.rigidbody)
hit.rigidbody.AddForceAtPosition(myTransform.forward * bulletForce, hit.point, ForceMode.Impulse);
//Linger around for a while to let the trail renderer dissipate (if the bullet has one.)
Destroy(gameObject, timeToDestroyAfterHitting);
}
// Update is called once per frame
void Update()
{
Move();
}
//Move is a seperate method as the bullet must move IMMEDIATELY.
//If it does not, the shooter may literally outrun the bullet-momentarily.
//If the shooter passes the bullet, the bullet will then start moving and hit the shooter in the back.
//That would not be good.
void Move()
{
//Check to see if we're going to hit anything. If so, move right to it and deal damage
if (Physics.Raycast(myTransform.position, myTransform.forward, out hit, speed * Time.deltaTime, layerMask.value))
{
myTransform.position = hit.point;
StartCoroutine(ApplyDamage());
}
else
{
//Move the bullet forwards
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
//Home in on the target
if (target != null)
{
//Firgure out the rotation required to move directly towards the target
targetRotation = Quaternion.LookRotation(target.position - transform.position);
//Smoothly rotate to face the target over several frames. The slower the rotation, the easier it is to dodg.
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, homingTrackingSpeed * Time.deltaTime);
Debug.DrawRay(transform.position, (target.position - transform.position).normalized * minDistToDetonate,Color.red);
//Projectile will "detonate" upon getting close enough to the target..
if (Vector3.SqrMagnitude(target.position - transform.position) < minDistToDetonateSqr)
{
//The hitEffect should be your explosion.
Instantiate(hitEffect, myTransform.position, myTransform.rotation);
GameObject.Destroy(gameObject);
}
}
}
//To avoid costly SqrRoot in Vector3.Distance
public void SetDistToDetonate(float x)
{
minDistToDetonateSqr = x * x;
}
//Call this method upon instantating the bullet in order to make it home in on a target.
public void SetAsHoming(Transform t)
{
target = t;
SetDistToDetonate(minDistToDetonate);
}
}
}
Here is my PlayerHealth code the name of my player script is HealthingScript
COde is :
#pragma strict
var hitPoints : float;
var maxHitPoints : int;
var regeneration : boolean = false;
var regenerationSpeed : float;
var aSource : AudioSource;
var painSound : AudioClip;
var fallDamageSound : AudioClip;
var deadReplacement : Transform;
var mySkin : GUISkin;
private var radar : GameObject;
var damageTexture : Texture;
private var t : float = 0.0;
private var alpha : float;
private var isDead : boolean = false;
private var scoreManager : ScoreManager;
var camShake : Transform;
function Start(){
if(regeneration)
hitPoints = maxHitPoints;
alpha = 0.0;
}
function Update(){
if (t > 0.0){
t -= Time.deltaTime;
alpha = t;
}
if(regeneration){
if( hitPoints < maxHitPoints)
hitPoints += Time.deltaTime * regenerationSpeed;
}
}
public function PlayerDamage (damage : int) {
if (hitPoints < 0.0) return;
hitPoints -= damage;
aSource.PlayOneShot(painSound, 1.0);
t = 2.0;
if (hitPoints <= 0.0) Die();
}
//Picking up MedicKit
function Medic (medic : int){
hitPoints += medic;
if( hitPoints > maxHitPoints){
var convertToScore : float = hitPoints - maxHitPoints;
scoreManager = gameObject.Find("ScoreManager").GetComponent(ScoreManager);
scoreManager.addScore(convertToScore);
hitPoints = maxHitPoints;
}
}
function Die () {
if(isDead) return;
isDead = true;
if(scoreManager == null)
scoreManager = gameObject.Find("ScoreManager").GetComponent(ScoreManager);
scoreManager.PlayerDead();
Instantiate(deadReplacement, transform.position, transform.rotation);
Destroy(gameObject);
}
function OnGUI () {
GUI.skin = mySkin;
GUI.Label (Rect(40, Screen.height - 50,60,60)," Health: ");
GUI.Label (Rect(100, Screen.height - 50,60,60),"" +hitPoints.ToString("F0"), mySkin.customStyles[0]);
GUI.color.a = alpha;
GUI.DrawTexture(new Rect(0,0,Screen.width, Screen.height), damageTexture);
}
function PlayerFallDamage(dam : float){
PlayerDamage(dam);
if(fallDamageSound) aSource.PlayOneShot(fallDamageSound, 1.0);
}
function Shake(p : float) {
var t : float = 1.0;
var shakePower : float;
while (t > 0.0) {
t -= Time.deltaTime;
shakePower = t/50;
camShake.rotation.x += Random.Range(-shakePower, shakePower);
camShake.rotation.y += Random.Range(-shakePower, shakePower);
camShake.rotation.z += Random.Range(-shakePower, shakePower);
yield;
}
}
I am not a noob but I don`t know why I can`t able to do this
Any comment and solution is appreciated here! Thanks!
BulletScript.cs line 15 is the problem. I don't think that's the way to reference a script.
And there's something else, though I'm not entirely sure about this (please correct me if I'm wrong), but don't Unity Javascript and C# have a different loading order? $$anonymous$$eaning that you can't call js from c# but you can do it the other way around.
EDIT: https://answers.unity.com/questions/48874/accessing-javascript-variable-from-c-and-vice-vers.html
Answer by Full8uster · Dec 08, 2017 at 02:05 PM
On your bullet script you need to refer your "HealthingScript hs" with GetComponent.
hs = (playerObjectWhereScriptIs).GetComponent<HealthingScript>() as HealthingScript ;
You can do this on Start Function for example.
Then when you want give damage you just call hs.(Lifevar) and apply the damage.
@Full8uster Please tell me what is the meaning of playerObjectWhereScriptIs. Please help in my I`ll give your name in credits. Please!
It's the object where your script HealthingScript is attached to.
Try it:
hs = GameObject.FindWithTag("Player").GetComponent<HealthingScript >() as HealthingScript ;
@Full8ster Thanks it worked, Would you like to join my Discord server you have helped me a lot! Thanks! here is link https://discord.gg/jYUU69f
Answer by meat5000 · Dec 08, 2017 at 12:58 PM
Just use GetComponent
https://unity3d.com/learn/tutorials/topics/scripting/getcomponent
Its a good idea to learn to use it yourself rather than relying on code handouts. There's a lot of information/guides/tutorials/documentation/Videos/Blogs/Unity-Answers questions/Manual Pages/Examples all detailing the usage of that one and very same GetComponent including thousands of examples of why they couldnt make it work and fixed it.
It is extremely useful. You can use it on the fly or you can 'cache' scripts in Start() for later access and use. Once a script is 'acquired' with GetComponent you can access it with the dot-operator ( . ), like in Java.
@meat500 how tell me full code. plz so that I can accept ur answer.
Answer by Kingofweirdos · Dec 08, 2017 at 09:20 AM
I have not fully read your description but based on what I read you can just do gameobject.find.hitpoints - whatever the damage variable is, I suggest that you keep 1 consistent variable that changes value based on state for damage
@$$anonymous$$ingofweirdos Soory to say but I didnt understand. Give me some examples.
You need to read the manual and the scripting reference. I'm not sure you understand 'your' code so you need to go back and start reading, rather then trying to get the community to do it for you without learning anything for yourself.