I am making a ball move when it collides with the player and pressed the key i, however i have done debug.log tests with the scripts and it appears that the OnCollisionEnter is not working. Here is the script
using UnityEngine;
using System.Collections;
public class KickForce : MonoBehaviour {
// Use this for initialization
void Start () {
print ("This is printed");
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter (Collision collision) {
if(collision.gameObject.tag == "Player")
{
print ("this has not worked");
if (Input.GetKey ("i")) {
print("this has not appeared on the console");
transform.Translate(Vector3.right * Time.deltaTime * 10);
}
}
}
}
Assuming your objects have colliders and rigidbodies and collision
genuinely is tagged as Player
then "this has not worked"
will print. There is nothing wrong with that part of the code.
However the code below your input is not going to work. OnCollisionEnter is only called once, on the frame at which they collided.
Your input if (Input.GetKey ("i")) {
is therefore only going to be called once at most too, only really if the player was holding down the key when the collision happened. The chances of the player being able to hit i at the exact same frame that the collision occurred are pretty much zero.
This means that transform.Translate(Vector3.right * Time.deltaTime * 10);
is only possibly going to happen once too. Time.deltatime is also going to dramatically scale down the value of the translate. At 60 frames per second you are going to be moving the ball right by 0.16… which probably isn’t even going to be noticeable.
You should set a boolean on collision rather than trying to put the input directly below it and use something like AddForce to kick the ball as just arbitrarily telling the ball to move right is going to look very rigid and unnatural. I would also put this script on the player, not the ball.
Here’s a quick example for you:
using UnityEngine;
using System.Collections;
public class PlayerScript: MonoBehaviour
{
private bool ballCheck;
private Rigidbody ball;
private float kickPower = 5;
private Vector3 direction;
// Use this for initialization
void Start()
{
//This will need to be set to the direction you want to kick the ball in
direction = transform.forward;
}
//Make sure your ball object has a rigidbody, collider and is tagged "Ball"
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Ball")
{
ballCheck = true;
ball = collision.gameObject.GetComponent<Rigidbody>();
}
}
void OnCollisionExit(Collision collision)
{
if (collision.gameObject.tag == "Ball")
{
ballCheck = false;
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
if (ballCheck == true)
{
ball.AddForce(direction * kickPower);
}
}
}
}
…and for future reference if I had noticed that you had asked this question twice in one day without making any changes or improvements yourself I would not have bothered answering it.