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;
}
}
}