Can't change value of a variable outside of Start

Hi thats my first question ever on this kind of forum. I’m trying to make a simple pong game. My problem is I seemingly can’t change variable value outside of Start function. Sure if I simply assign it with simple number e.g a=2 it works, but when I try to reach to some component values I can only achieve that in Start function.

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  


public class BallController : MonoBehaviour  

{  

    [SerializeField]  

    string strTag;  

    Rigidbody2D m_rigidbody;   

    Vector2 speed;  

    float a, b;  


    void Start()
    {
        m_rigidbody = GetComponent<Rigidbody2D>();
        if (Random.Range(-1, 2)>0)
        speed = new Vector2(5, Random.Range(-6, 0) + 3);
        else
        speed = new Vector2(-5, Random.Range(-6, 0) + 3);
        m_rigidbody.velocity=speed;
       /* a = m_rigidbody.velocity.x;
        b = m_rigidbody.velocity.y; 
        speed = new Vector2(-a, -b); // if I put it in here it works when it touches the Paddle velocity changes(of course only once) */
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == strTag)
        {
            a = m_rigidbody.velocity.x;
            b = m_rigidbody.velocity.y;
            speed = new Vector2(-a, -b); //but why it doesn't work anymore here :///
            m_rigidbody.velocity = speed;
        }
    }
    
}

Hello.

I think most probably is that your function is not reaching that line of code.

If you replace

a = m_rigidbody.velocity.x;
b = m_rigidbody.velocity.y;
speed = new Vector2(-a, -b); //but why it doesn't work anymore here :///
m_rigidbody.velocity = speed;

for

Debug.Log("Hello");

is it working?

I’m also sure if you do this, will see it works when you press “p” key:

void Update()
{
if (Input.GetKeyDown(KeyCode.p))
  {
  a = m_rigidbody.velocity.x;
  b = m_rigidbody.velocity.y;
  speed = new Vector2(-a, -b); //but why it doesn't work anymore here :///
  m_rigidbody.velocity = speed;
  }
}

so the problem is that you are not triggering the Ontrigger or your condition is not true.

Debug the code, make sure you have all condition to execute the OnTrigger function.

Bye

I have personally noticed sometimes that over doing the code can sometimes limit it. Especially when calling a GetComponent as it is too slow to calculate in one pass of compiling. I first would simplify your declaration:

if (collision.collider.tag == strTag)
         {
             m_rigidbody.velocity = new Vector2(-m_rigidbody.velocity.x, -m_rigidbody.velocity.y);
         }

If it still is not working, debug the values during playtime so you can see exactly what the velocity is showing it’s doing. You’ll be surprised what the values actually are, sometimes. But you shouldn’t have any issue changing values after Start(), because that only runs once in the beginning.