I have an object I want to instantiate and I want it to take on a value. The serialized field I made is just so that I could put in a game object to reference location for respawning. I’d like to assign a value to a object even if it can only be modified in code.
In code, how could I write something to fill a value into the serialized fields I showed in the picture?
Script:
using UnityEngine;
public class Ball : MonoBehaviour
{
[SerializeField] public Transform RespawnPoint;
// config parameter
[SerializeField] float pushX = 0.1f;
[SerializeField] float pushY = 10f;
[SerializeField] float randomFactor = 0.2f;
[SerializeField] float LowRandomFactor = -0.2f;
TrailRenderer MyBallTrail;
// cached component references
Rigidbody2D rb;
private bool hasStarted = false;
void Start()
{
// rigidbody to rb
rb = GetComponent<Rigidbody2D>();
MyBallTrail = GetComponent<TrailRenderer>();
}
// Update is called once per frame
void Update()
{ // ball lock & stick
if (!hasStarted)
{
LockBallToPaddle();
LaunchOnClick();
MyBallTrail.time = 0f;
}
else if (hasStarted){
MyBallTrail.time = 0.2f;
}
Debug.Log("Your boolean hasStarted is set to " + hasStarted);
}
public void LaunchOnClick()
{
if (Input.GetKeyDown("space"))
{
hasStarted = true;
GetComponent<Rigidbody2D>().velocity = new Vector2(pushX, pushY);
}
}
public void LockBallToPaddle()
{
Vector2 paddlePos = new Vector2(RespawnPoint.transform.position.x, RespawnPoint.transform.position.y);
transform.position = paddlePos;
}
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 velocityAdjustment = new Vector2
//X axis
(Random.Range(LowRandomFactor,randomFactor),
//Y axis
Random.Range(0, randomFactor));
if (hasStarted)
{
rb.velocity += velocityAdjustment;
}
else if (collision.transform.CompareTag("DeathBarrier"))
{
hasStarted = false;
}
}
public void ResetPosition()
{
hasStarted = false;
Vector2 paddlePos = new Vector2(RespawnPoint.transform.position.x, RespawnPoint.transform.position.y);
transform.position = paddlePos;
}
}
EDIT: I actually ended up replacing the paddle1 variable and updated the script. I only need to fill a single value to respawn the object at this point, so one serialized field. Thanks!!!