I have already tried to look into this... but no luck..
Sprite renderer, and mover references, work fine they appear in the inspector as I want them to.
However I am having issues in FILE 2 I am unsure of how to Serialize the Animator in the inspector.
FILE 1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "EnemyConfig", menuName = "Enemies/Enemy config", order = 0)]
public class EnemyConfig : ScriptableObject
{
public float moverSpeed;
//public float zRotation;
public Sprite sprite;
public Animator animator;
}
FILE 2
//EnemyController.CS
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
[HideInInspector]
public EnemyConfig config;
[SerializeField]
private SpriteRenderer spriteRenderer;
//Want to get a reference to the animator component appear in the inspector
//This is my issue...--------------------------------------]
[SerializeField]
private GetComponent<Animator> animatorController;
//----------------------------
private Mover mover;
private void Start()
{
mover = GetComponent<Mover>();
if(mover != null)
{
mover.speed = config.moverSpeed;
}
if(config.sprite != null)
{
spriteRenderer.sprite = config.sprite;
}
// related to the animator
if(config.animator != null)
{
animatorController.animator = config.animator;
}
}
}
Here you can see how the Sprite reference, and mover reference appear in the inspector.
I am trying to do the same with the Animator
GetComponent<T> is a method, it is not a type. So, you can't declare a field with this as its type. I would be surprised if this code actually even compiles. What you want is simply
[SerializeField]
private Animator animator;
Note that AnimatorController is an Editor-only class; you can't include it in your game code. Hence why you want Animator here.
Another thing to consider is, is the Animator component going to be on the same game object? If so, you don't need to serialize the reference - that would only be useful if it's going to be on a different game object, and you need to store that link at edit time.
If the Animator component is on the same object, you can do this:
private Animator animator;
void Start()
{
animator = GetComponent<Animator>();
}
The advantage is that you won't have to make sure the reference stays up-to-date, it will be connected whenever the gameplay starts. This, by the way, is the correct use of GetComponent<T> - since it's a method, you can call it within another method, not where you had it in your File2.
Related
I'm currently making a 3D endless runner game with the choice to select different skins for the player. Everything's going smoothly until I come across a problem, in which I try to assign two collision game objects to each character prefab in the container that can detect the player's collision box when it collides with a powerup.
It only detects the first playerContainer's (Milo) 'Coin Detect' game object (eventhough it's been deactivated) and does not recognize the 'Coin Detect' collision game object in the Baddie playerContainer (which the player has chosen to play)
So my question is, how am I able to get the script to recognize the child that's active in the third playerContainer game object instead of it automatically detecting the first playerContainer game object's child?
From the Magnet powerup script I've made, the script detects the first playerContainer's 'Coin Detect' game object only. As shown in the attached picture below:
Here's my current script where the player is able to select their preferred characters.
using System.Collections.Generic;
using UnityEngine;
public class EnablePlayerSelector : MonoBehaviour
{
public GameObject[] players;
public int currPlayerCount;
void Start()
{
currPlayerCount = PlayerPrefs.GetInt("SelectedPlayer", 0);
foreach (GameObject player in players)
player.SetActive(false);
players[currPlayerCount].SetActive(true);
}
}
and here's the script where I deactivate the 'Coin Detect' collision game Object and activate it when the player collides with the powerup.
using System.Collections.Generic;
using UnityEngine;
public class Magnet : MonoBehaviour
{
public GameObject coinDetect;
void Start()
{
coinDetect = GameObject.FindGameObjectWithTag("CoinDetect");
coinDetect.SetActive(false);
Debug.Log("False");
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
StartCoroutine(coinActivate());
Destroy(transform.GetChild(0).gameObject);
}
}
IEnumerator coinActivate()
{
Debug.Log("Hi");
coinDetect.SetActive(true);
yield return new WaitForSeconds(5f);
coinDetect.SetActive(false);
}
}
Well your issue is rather that you are doing GameObject.FindGameObjectWithTag("CoinDetect") which will return whatever is the first encountered CoinDetect in your scene in this moment. So unless EnablePlayerSelector.Start is executed before the Magnet.Start it will always be the first one since they are still all active by then.
You could probably already solve your issue by following the general thumb-rule:
Do things where you do not depend on other components already in Awake
Do things where you o depend on other components in Start
This way you already cover most of the use cases and are sure that components are self-initialized (Awake) before anything is accessing them in Start.
So simply change the EnablePlayerSelector.Start into Awake and you should be fine.
In very specific cases you might still have to adjust the Script Execution Order or use events.
Instead of doing this at all though I would rather in the moment of the collision request the current one from the PlayerContainer directly:
// put this on each player root object
public class Player : MonoBehaviour
{
// reference these via the Inspector
[SerializeField] private GameObject coinDetector;
[SerializeField] private GameObject playerrange;
// ... and in general any information bout this Player that is relevant for other scripts
// Readonly accessor property
public GameObject CoinDetector => coinDetector;
}
and then rather have
public class EnablePlayerSelector : MonoBehaviour
{
[SerializeField] private Player[] players;
[SerializeField] private int currPlayerCount;
public Player CurrentPlayer => players[currPlayerCount];
// In general do things where you don't depend on other scripts already in Awake
// This way you could actually already solve your issue by keeping things where you do
// depend on others in Start
private void Awake()
{
currPlayerCount = PlayerPrefs.GetInt("SelectedPlayer", 0);
for(var i = 0; i < players.Length; i++)
{
players[i].gameObject.SetActive(i == currPlayerCount);
}
}
}
and then finally do e.g.
public class Magnet : MonoBehaviour
{
public float effectDuration = 5f;
private IEnumerator OnTriggerEnter(Collider other)
{
var playerSelector = other.GetComponentInParent<EnablePlayerSelector>();
if(!playerSelector) yield break;
Debug.Log("Hi");
Destroy(transform.GetChild(0).gameObject);
var coinDetect = playerSelector.CurrentPlayer.CoinDetector;
coinDetect.SetActive(true);
yield return new WaitForSeconds(effectDuration);
coinDetect.SetActive(false);
}
}
or alternatively if the other in this case refers to the object with the Player component anyway you could also directly do
public class Magnet : MonoBehaviour
{
public float effectDuration = 5f;
private IEnumerator OnTriggerEnter(Collider other)
{
if(!other.TryGetComponent<Player>(out var player)) yield break;
Debug.Log("Hi");
Destroy(transform.GetChild(0).gameObject);
var coinDetect = player.CoinDetector;
coinDetect.SetActive(true);
yield return new WaitForSeconds(effectDuration);
coinDetect.SetActive(false);
}
}
So I have a CharacterController Class that just deals with User inputs and If the player is hit by a bullet and reduces the Health of that Character. I need to use this Health Value in another Script so Have used the following code to try this however I get a CS01061 as it says it cannot find the Health variable.
Character Controller Class Variables:
public class CharacterController : MonoBehaviourPunCallbacks
{
public float MovementSpeed = 2;
public float JumpForce = 5;
public float Health = 100f;
public float height = 10;
public static GameObject LocalPlayerInstance;
Here is the code for the PlayerManager Class that needs Health from above:
//Gloabl Variables
public GameObject ActualPlayer;
public CharacterController Controller;
public float Health;
public void Awake()
{
ActualPlayer = GameObject.Find("Player");
Controller = ActualPlayer.GetComponent<CharacterController>();
Health = Controller.Health;
......
Player is a prefab that is a GameObject that has been initialised by Photon and has the CharacterController script as a component. Why can't unity see that the script has a health variable?
Are you sure it is looking for the correct type and not maybe one with the same name but from a different namespace?
Unity itself already has a built-in type named CharacterController in the namespace UnityEngine so most probably your second script is using that type since on the top you will have a
using UnityEngine;
Make sure you are referencing the correct one in your script.
You could e.g. put yours into a specific namespace like
namespace MyStuff
{
public class CharacterController : MonoBehaviourPunCallbacks
{
...
}
}
and then in your other script explicitly use
public MyStuff.CharacterController Controller;
and
Controller = ActualPlayer.GetComponent<MyStuff.CharacterController>();
Health = Controller.Health;
Besides that remember that float is a value type, not a reference, so most probably you storing that value in a field in your second script is not what you want to do ;)
rather always simply access the Controller.Health instead.
I trying to get the enemy ship to shoot the player ship tagged player
I receive one error: Assets/Scripts/EnemyAttack.cs(11,13): error CS0246: The type or namespace name `EnemyAtack' could not be found. Are you missing an assembly reference? I tried creating a class for the enemy attack but did not work. Any feedback is appreciated.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAttack : MonoBehaviour
{
[SerializeField] GameObject[] enemyGuns;
// Start is called before the first frame update
void Start()
{
AddSphereCollider();
}
private void AddSphereCollider()
{
Collider sphereCollider = gameObject.AddComponent<SphereCollider>();
sphereCollider.isTrigger = false;
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "player")
{
Destroy(col.gameObject);
}
}
}
Stop() and PlayOneShot() are both functions associated with the AudioSource class.
AudioSources are used to play AudioClips, in this case you need to add an AudioSource reference to your monobehaviour and add an AudioSource to your prefab, then link the reference and call your PlayOneShot() and Stop() functions on the AudioSource instead.
The other issue is your AudioClip is named LaserSound and your Monobehaviour is also called LaserSound.
Rename one or the other.
Change
[SerializeField] private AudioClip LaserSound;
to
[SerializeField] private AudioClip laserSound;
and that should work. "AudioClip LaserSound" is basically the equivalent of "Classname AnotherClassname"
Brand new to C# and Unity.Please be nice I've been at this all night. Every tutorial I poor through says changing an object from invisible to visible is as simple as setting the game object to on. However Unity gives me an error when I declare a game object in this script. The objective is, when the trigger is entered, several game objects called 'spawn' will become visible.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collider : MonoBehaviour
{
public gameObject Spawn; // I get error On this line that type is expected,
//not property. It wants a Transform>
private Rigidbody rb;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void OnTriggerEnter(BoxCollider other)
{
if (other.gameObject.CompareTag("Player"))
{
Spawn.SetActive(true);
}
}
}
gameObject isn't a type, but GameObject is.
Get rid of public gameObject Spawn; and use public GameObject Spawn; to declare a GameObject property called Spawn
I'm trying to learn how to use Unity and following online tutorials but I am currently having a problem that I don't understand how to fix.
I have a Sprite in my scene and I have attached a script to it however in the Inspector it shows the script is there but I cannot see the variables inside? I had this problem previously and it sorted itself out.
What is the cause of this problem/how do I fix it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpaceShip : MonoBehaviour {
public float speed = 30;
public GameObject theBullet;
private void FixedUpdate()
{
float horzMove = Input.GetAxisRaw("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2(horzMove, 0) *
speed;
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Jump"))
{
Instantiate(theBullet, transform.position, Quaternion.identity);
}
}
}
Edit: The problem was solved by reimporting.
You either need to declare the variables as Public or [SerializeField] for member variables to appear in the inspector. Note that by declaring something as public allows access to the variable from outside the class (from other scripts/classes for example). By default, private is assigned to member variables.
Example:
public class testscript : MonoBehaviour
{
public int foo; // shows up in inspector
[SerializeField] private int bar; // also shows up while still being private
void Start()
{
}
}
Not is a problem, You forget to do something surely.
It is common at first with Unity.
Start again.
In the scene create a new GameObject and add you script.
If the inspector shows not variable:
The varible do not is public (false, if is public in you script)
There is some syntax error in the script!
or
You were not adding the correct script to the GameObject.
There are not many secrets to that, if all is well enough that the variable is public and this outside of a method of the script so that it is seen in the inspector.
One tip, do not use a GetComponent or Instantiate inside a FixedUpdate or Update because they are expensive, save the Rigidbody2D in a variable in the Start and then use it.
Sorry for my English and good luck.