Sorry for my English . XD XD. I making my 2D Game with Sprites ( RigidBody and Box-Circle Collider ) .
I’m beginner. So sorry for my error or simple script or class without sense.
How pick up the Ball with my Character and how pull this? The ball must position themselves to the right or left of my character.
I thought to put one Box Collider 2D with IsTrigger Actived in Character.
And when the Ball touches the trigger is added to Character.
But my Script don’t work.
I created one class called Ball with private GameObject ball and I assigned to a Ball.
public class Ball : MonoBehaviour {
private GameObject ball;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
The error on Unity is : NullReferenceException: Object reference not set to an instance of an object
Grab.OnTriggerEnter2D (UnityEngine.Collider2D Ball) (at Assets/Code/Grab.cs:12)
Is the player.GetComponentInParent ();
OnTriggerEnter2D already gives you the object that entered it,
So maybe you want something like,
void OnTriggerEnter2D (Collider2D other)
{
if (other.compareTag("Ball"))
{
other.transform.parent = player.transform;
// might want to set ball rigidbody to kinematic here also
}
}
I also tried this method.
But unity generate an error.
NullReferenceException: Object reference not set to an instance of an object
Grab.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Code/Grab.cs:15)
player is null. If this script is attached to the player gameobject, you can just use “transform” or “gameObject.transform”, otherwise, you need to make the player field public, and add the player object via the editor, or use “FindObjectOfType” in the Start Method: Unity - Scripting API: Object.FindObjectOfType
Now the ball is attached to the character.
But it does not follow it, stays there.
How do I solve this problem?
The ball must position themselves to the right or left of my character.
This is because it is not Kinematic.
Because the ball is formed in this way .
Now the first problem is solved, but is exit other problem.
Unity with Script assign the ball only with Circle Collider to the Character, but remains the Ball with RigidBody2D and Circle Collider, so when I go near it, i’m subjected to its mass, its physics.
P.S
And I’m not thinking about throwing the ball.
I believe that to pull the ball, must have a RigidBody2D.
So will be other problem.
But i’m going to step.
Ok, I think I’ve solved the problem, just like that.
public class Grab : MonoBehaviour {
public GameObject player;
public GameObject BallDestroyed;
void OnTriggerEnter2D (Collider2D other)
{
if (other.CompareTag ("Ball"))
{
other.transform.parent = player.transform;
Destroy (BallDestroyed);
}
}
}
Now Ball with RigidBody2D and Circle Collider is Deleted when i take the Ball.
Now I have to place the right and left of the character.
How do I this?
And How Shoot the ball?