It should detect if car speed is if lower than 50 - 50 “HP”
if lower than 100 - 100 “HP”.And if “HP” is lower than 0 it should change var “Wrecked” to true but it doesnt and if “Wreck” is true it should disable “CarControl” Script.Can someone help me?
I’m beginer and sorry for my english
Code:
#pragma strict
var HP = 100;
var Wreck = false;
if(HP < 0)
{
Wreck = true;
}
if(Wreck == true)
{
Debug.Log("Cant drive");
}
function Update () {
}
function OnCollisionEnter(col: Collision){
if (col.gameObject.tag == "Wall"){
Debug.Log("I like Wall");
if(GetComponent(CarControl).Speed < 50)
{
Debug.Log("50");
HP -= 50;
}
if(GetComponent(CarControl).Speed < 100)
{
Debug.Log("100");
HP -= 100;
}
}
}
Lots of very core things wrong here. I’m surprised it even compiles at all.
This part is fine:
#pragma strict
var HP = 100;
var Wreck = false;
This part looks as though it’s not even within a method body.
if(HP < 0)
{
Wreck = true;
}
if(Wreck == true)
{
Debug.Log("Cant drive");
}
Here’s an empty Update method which should probably contain the orphaned code above.
function Update () {
}
While not technically wrong, you should probably have CarControl cached so that you can more quickly access it each time there is a collision. GetComponent is slow!
function OnCollisionEnter(col: Collision){
if (col.gameObject.tag == "Wall"){
Debug.Log("I like Wall");
if(GetComponent(CarControl).Speed < 50)
{
Debug.Log("50");
HP -= 50;
}
if(GetComponent(CarControl).Speed < 100)
{
Debug.Log("100");
HP -= 100;
}
}
}
So how can we fix this?
#pragma strict
var hp : int = 100;
var carControl : CarControl;
function Awake()
{
carControl = GetComponent(CarControl);
if (carControl == null)
{
Debug.LogError("No CarControl Component found!");
gameObject.SetActive(false);
}
}
function OnCollisionEnter(col: Collision)
{
if (col.gameObject.tag == "Wall")
{
Debug.Log("I like Wall");
// the only reason the below logic really isn't ideal, but it'll work because if the value is 51 it won't pass the first check,
// but will pass the second.
if(carControl.Speed < 50)
{
Debug.Log("50");
hp -= 50;
}
else if(carControl.Speed < 100)
{
Debug.Log("100");
hp -= 100;
}
}
enabled = hp > 0;
}