I’m new to Unity and scripting/programming, but can at least understand basic concepts and scripts.
So I’m trying to make a 2D game similar to basketball. I need help with scripting a ball going into a box(trigger) that registers a +1 score and resets/respawns the ball to it’s position from game start(not sure if I have to script ball spawn point too.).
Will accept both C# and UnityScript. Thanks!
make ball with rigidbody and collider, set ball`s tag “ball”. Create prefab for ball. Make box with collider, set box colider to trigger. Make empty gameobject for spawn.
script for box will be some thing like:
public int score;
public Transform ballspawn;
public GameObject ball;
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "ball")
{
score +=1;
Destroy (other.gameObject);
Instantiate (ball, ballspawn.transform.position, ballspawn.transform.rotation);
}
}
i didnot check it, may be it is somewhere wrong.
Not sure if I did it properly but I got an error,
“A namespace can only contain types and namespace declarations”
Edit:
I tried checking if everything is fine. Unity told me that Destroy and Instantiate didn’t exist in current context. So I tried removing both to check if the box recognized the ball as something that would activate the trigger. It does. I’ll try fiddling a bit more with the code. But if you can help me some more, I’d totally appreciate it
using UnityEngine;
using System.Collections;
public class insideBorder : MonoBehaviour{
public int score;
public Transform ballspawn;
public GameObject ball;
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "ball")
{
score +=1;
destroy(other.gameObject);
instantiate (ball, ballspawn.transform.position, ballspawn.transform.rotation);
Debug.Log("Positive");
}
}
}
The code that vakabaka gave you isn’t the full class. Put that code inside your class declaration. Just leave everything that Unity3d creates and paste the code inside the class like
class YourClassName extends … {
// place in here
}
i am newbie too
try __D__estroy __I__nstantiate. I have just make it wrong. I have edited my script.
ps. i think, if you have scripted something and it works with 1st run, then something is bad
Wew it kind of works now it destroys the ball and gives score(?). But still trying to figure out how to make it respawn.
Still super thanks vakabaka
- Instantiate (ball, ballspawn.transform.position, ballspawn.transform.rotation); this line should work for respawn.
create prefab, drag&drop your ball to the prefab. Create empty for spawnpoint. Drag&drop ballprefab and emptypoint to the script in unity inspector. If you start your game in unity, destroy the ball and check hierarchy. The game schould create ball(clone), if one is destroyed. May be you can not see the ball, if it is behind the camera on z-direction (in that case move empty-point).