When a key is pressed, I want a sphere to instantiate at run time, from the game object the script is assigned to. After the space bar is pressed is where I want the event to happen. I’ve been searching for it. I got close, but it was just a game object with no mesh. I’m new to C# (new to Unity 3D, and scripting altogether).
using UnityEngine;
using System.Collections;
public class FixedList : Object {
private int listSize = 0;
private int[] items = new int[256];
public int ListSize
{
get { return listSize; }
}
}
public class ProjectileFireScript : MonoBehaviour {
public GameObject Projectile;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if ( Input.GetKey("space"))
{
public new GameObject = new Projectile;
}
}
}
I don’t think the above is right, exactly.
Any help is greatly appreciated. Thanks.
P.S. If you could/can explain some of the lines of code as well, that will help me in the future.
If it’s a sphere you need, there is a specific function in the GameObject class that creates primitives : GameObject.CreatePrimitive().
using UnityEngine;
using System.Collections;
public class FixedList : Object {
private int listSize = 0;
private int[] items = new int[256];
public int ListSize
{
get { return listSize; }
}
}
public class ProjectileFireScript : MonoBehaviour {
public GameObject Projectile;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if ( Input.GetKey("space"))
{
// Variables declared inside functions don't need to be declared new or public, as their scope is completely within the function.
Gameobject newSphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
// To set the position of the sphere to the same of the gameobject that this script resides on
newSphere.transform.position = transform.position;
// Now I assume this is a projectile, so you will want to add a script to control what each projectile will do, lets say it's a class named "ProjectileUpdater.cs"
newSphere.AddComponent(typeof(ProjectileUpdater));
// We should also face the projectile in the right direction, so set it's rotation to the same as the firing object
newSphere.transform.rotation = transform.rotation;
}
}
}
Then for projectile updater you could have some movement code, maybe a destroy after x amount of time.
using UnityEngine;
public class ProjectileUpdater : MonoBehaviour
{
private float timer;
private float timeToLive;
void Start()
{
timer = 0.0f;
timeToLive = 3.0f;
}
void Update()
{
// We already have the object facing the correct way, so just use it's forward vector to move in a straight line.
transform.Translate(transform.forward * Time.deltaTime);
timer += Time.deltaTime;
if(timer > timeToLive)
{
// This will make the object self destruct after the amount set in timeToLive (3.0 sec in this case).
Destroy(gameObject);
}
}
}
Hopefully this will set you in the right direction. Feel free to ask some more questions about the code if you need.