Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hey,

I am trying to make an object that bounces back when it hit the boundaries. Here is the code that I tried running:

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public Rigidbody rb;
    public bool isBouncing = false;

    private float bounce = 6f;
    private object collision;

    private void OnCollisionEnter(Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "sideObstacle")
        {
            rb.AddForce(collision.[0].normal * bounce);

            isBouncing = true;

            Invoke("StopBounce", 0.3f);

        }
    }


    void StopBounce()
    {
        isBouncing = false;
    }

}



but it shows this error


struct System.Int32
Represents a 32-bit signed integer.
CS1001: Identifier expected 


Can someone pls explain what is the problem and how can I solve it?

Just for some information - It also shows error(CS1001)

What I have tried:

Though I have tried reading some documentation and some other content also but I didn’t got the expected results. Please help.
Posted
Updated 31-May-21 8:23am
Comments
[no name] 31-May-21 13:12pm    
rb.AddForce(collision.[0].normal * bounce);

No "." before "[0]"; if that's a dimension.
HardykMahendru 31-May-21 23:55pm    
If I remove the “.” it shows the error
cannot apply indexing to an expression of type 'object'

Pls try to give clearer answers
Richard Deeming 1-Jun-21 11:06am    
Please try to ask clearer questions! 🤣

As that error says, you cannot apply indexing to an object variable. But by adding the . before the indexer, you've simply replaced one error with another.

You need to use the correct type for your collision field. And you need to initialize it to something - with the code you've shown, it will always be null, so even if you could get your code to compiler, you'd get a NullReferenceException.

1 solution

If you want the normal angle of the contact you need something like
C#
rb.AddForce(collisionInfo.contacts[0].normal * bounce);


That gets the normal angle of the first contact, if there are multiple contact points you might need to do some other analysis to work out which contact you want the normal force for.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900