- Home /
Instatiating a rigidbody (using C#)
hey guys what's up? I am trying to make a canon that shoots a sphere every time the player hits space. The console is showing that newball is an unexpected symbol:(just changed my code a bit but still didn't work):
public class BallShooter : MonoBehaviour {
public Rigidbody ball;
public float speed = 60;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Launcher();
}
IEnumerator Launcher(){
if(Input.GetKeyDown(KeyCode.Space)){
//rigidbody.transform.position = new Vector3(rigidbody.transform.position.x, rigidbody.transform.position.y, rigidbody.transform.position.z);
Rigidbody newball = Instantiate(ball, transform.position, transform.rotation)
newball.velocity = transform.TransformDirection(Vector3.forward * speed);
}
}
}
Didn't work bro. The console displays only one error: unexpected symbol newball at the velocity line: newball.velocity = transform.forward * speed;
Answer by alexzzzz · Jun 21, 2013 at 01:41 PM
I guess the purpose of your code is to fire a ball when a player presses Space, and destroy that ball in 3 seconds.
If it's correct then this code might do the job:
public class BallShooter : MonoBehaviour
{
public Rigidbody ball;
public float speed = 60;
public float lifetime = 3;
// Update is called once per frame
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
{
Rigidbody newball = (Rigidbody)Instantiate(ball, transform.position, transform.rotation);
newball.velocity = transform.forward * speed;
Destroy(newball.gameObject, lifetime);
}
}
}
Note that you have to cast the result of Instantiate(...) to the class you actually instantiate (Rigidbody in this case), and also note the semicolon at the end of that line.
So THAT's what they meant by cast!! lol 10x alot for explaining it mate.
Answer by BlackWingsCorp · Jun 21, 2013 at 12:52 PM
Ok fixed it. Here's how it was supposed to be:
using UnityEngine;
using System.Collections;
public class BallShooter : MonoBehaviour {
public Rigidbody ball;
public float speed = 60;
public Rigidbody balls;
void Start () {
}
void Update () {
Launcher();
}
void Launcher(){
if(Input.GetKeyDown(KeyCode.Space)){
balls = Instantiate(ball, transform.position, transform.rotation)as Rigidbody;
balls.velocity = transform.TransformDirection(Vector3.forward * speed);
}
}
}