- Home /
Question by
MA0012 · May 23, 2019 at 04:08 PM ·
variableserializationresetplaymode
Public Variables in MonoBehaviour Scripts reset to "None" in Playmode
I've read the answers to similar questions, but none of them have helped. I am making a simple two-player ball game and have added a screen shake effect to my camera. The script for this is attached to the main camera in my scene, and a prefab in my scene which I named "Ball" contains an OnTriggerEnter2D reference to the camera script and the effect works properly. However, entering Playmode in the editor causes the variable to reset to None and I need to manually drag my Camera into the appropriate slot on the Ball prefab whenever the game starts. I've tried declaring SerializeField before the variable as well as making the Camera itself a prefab, but this hasn't helped. My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[System.Serializable] public class Ball : MonoBehaviour
{
public Rigidbody2D ballBody;
public AudioClip hitSound;
public AudioSource source;
public TrailRenderer trail;
[SerializeField]
public CameraShake shake;
void Awake ()
{
shake = GetComponent<CameraShake>();
ballBody = GetComponent<Rigidbody2D>();
trail = GetComponent<TrailRenderer>();
}
void OnTriggerEnter2D (Collider2D c)
{
if (c.gameObject.tag == "Player")
{
ballBody.AddForce(new Vector2(1,1),ForceMode2D.Impulse);
}
else if (c.gameObject.tag == "Wall")
{
ballBody.AddForce(new Vector2(-1,-1),ForceMode2D.Impulse);
}
else if(c.gameObject.tag == "Goal")
{
trail.Clear();
ballBody.velocity = Vector3.zero;
ballBody.position = Vector3.zero;
shake.ShakeTrigger();
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612201949im_/https://answers.unity.com/themes/thub/images/avi.jpg)