- Home /
Spawned tree not falling
**I have two scripts, one to give the full tree health (Tree Health), which when it reaches 0 spawns a chopped tree. This works correctly and as expected, but when the chopped tree is spawned, the top half of the tree does not fall over D:! I have applied a capsule collider, a rigid body and the script (Push Tree) to the part of the tree that should fall (the stump stays) but it doesn't seem to fall. I have also applied a capsule collider to the stump of the cut tree. Anyway, here are the two scripts (C#):
Tree Health:
using UnityEngine;
using System.Collections;
public class TreeHealth : MonoBehaviour {
public int Health;
public GameObject FallenTree;
public Camera myCamera;
void Start () {
myCamera = GameObject.FindObjectOfType<Camera>();
}
void Update ()
{
if(Health > 0)
{
if(Vector3.Distance(transform.position, myCamera.transform.root.transform.position) < 15f)
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
Ray ray = new Ray(myCamera.transform.position,myCamera.transform.forward);
RaycastHit hit;
if(Physics.Raycast(ray,out hit,15f))
{
if(hit.collider.gameObject == gameObject)
{
--Health;
}
}
}
}
}
if(Health <= 0)
{
Health = 0;
Destroy(gameObject);
Instantiate(FallenTree,transform.position,transform.rotation);
}
}
}
And here is the Push Tree script I am presumably having problems with:
using UnityEngine;
using System.Collections;
public class PushTree : MonoBehaviour {
public float Force;
public Camera MyCamera;
void Start ()
{
MyCamera = GameObject.FindObjectOfType<Camera>();
GetComponent<Rigidbody>().AddTorque(MyCamera.transform.right * Force,ForceMode.Impulse);
}
// Update is called once per frame
void Update () {
}
}
If no one can find the problem in this code then any suggestions about the prefabs would also be gladly appreciated! :)
Answer by getyour411 · Aug 05, 2015 at 09:56 PM
Try moving your PushTree Start() code to Awake(). Instantiated objects and Start() sometimes have issues, sorry I can't explain the details but try it.
Do you mean replace the void start() with void awake()? If I have got it right then it didn't change anything...
Actually I just noticed you are applying your physics forces on $$anonymous$$yCamera, I assume you meant to do that on tree?
I have actually re-done my script now and it is quite different from this one, and the tree chopping works fine. But I do see that that was probably the problem anyway, I don't know how I missed it! :P. Anyway, I have a working script but thanks for your time nonetheless.
Your answer
Follow this Question
Related Questions
Game Object is Instantiating on same position 2 Answers
How to destroy a particular clone on touch/mouse? 1 Answer
Why is my Prefab Instantiating when the Scene is Loaded? 2 Answers
Change Transparency 1 Answer
Unity - Remove GameObject 0 Answers