So I am able to Instantiate new objects at runtime and they spawn in with the correct scripts attached however the scripts do now spawn in with the variables fixed in their slots.
I need a way to spawn prefabs with the scripts attached AND the variable slots in the script are all filled in.
Deploy capsule script (linked to main camera)
public class deployCapsule : MonoBehaviour
{
public GameObject CapsulePrefab;
public Path path;
public float respawnTime = 1.0f;
void Start()
{
StartCoroutine(capsuleWave());
}
private void spawnCap()
{
GameObject a = Instantiate(CapsulePrefab) as GameObject;
a.transform.position = new Vector2(1.0f, 1.0f);
path.followers.Add(a);
Debug.Log("1");
}
IEnumerator capsuleWave()
{
while (true)
{
yield return new WaitForSeconds(respawnTime);
spawnCap();
}
}
}
Path Follower script
public class PathFollower : MonoBehaviour
{
public float movementSpeed;
//private float pathProgress = 0;
public GameObject objectToSpawn;
public Transform[] positionPoint;
[Range(0,1)]
public float value;
void Start()
{
Debug.Log(iTween.PathLength(positionPoint));
}
void Update()
{
movementSpeed = 10f;
if (value < 1)
{
value += Time.deltaTime / movementSpeed;
}
iTween.PutOnPath(objectToSpawn, positionPoint, value);
}
private void OnDrawGizmos()
{
iTween.DrawPath(positionPoint,Color.green);
}
}
I KNOW THIS IS NOT TECHNICALLY POSSIBLE.
But I need a method to get this done one way or another.
I am quite new to unity and would appreciate any help given.
Thank you in advance.
in deployCapsule, store a reference to the array of points
public Transform[] positionPoint;
assign the values in the inspector.
and then once you've instantiated the prefab, give it the array like this
//this is in the SpawnCap function
//GameObject a = Instantiate(CapsulePrefab) as GameObject;
a.GetComponent<PathFollower>().positionPoint = positionPoint;
//rest of your function
alternatively, set the values in the Awake() or Start() function of the newly instantiated Capsule by getting a reference to a class that has the data.
void Start()
{
positionPoint = GameObject.Find("Spawner").GetComponent<deployCapsule>().positionPoint;
}
After instantiating your capsule prefab and assigning a reference to it named a (I suggest you change this naming to something more logical)
GameObject a = Instantiate(CapsulePrefab);
Assuming your prefab already has the PathFollower component attached, you could use the GameObject.GetComponent<T> method to access it.
var pathFollowerComponent = a.GetComponent<PathFollower>();
After which, you could populate the positionPoint[] Transform's array (assuming that's what you're after) with references to the "Points" GameObjects located in the hierarchy and the scene.
It's up to you how to go about this:
You could create a tag on each point, use GameObject.FindGameObjectsWithTag("Point");
Obtain the children from the "PathFollower" GameObject and add its child transforms to your array
Create a singleton instance or a "GameManager" class which stores the points located in a scene
If you create new points dynamically, create a listener and invoke events to add the new points to the array whenever they're instantiated.
Note that the mentioned above may not return the points in the order you placed them, so you may need to sort them! In general, there are many other ways which you can find by searching the forums, or on Google!
The issue here is that your prefab is in project while the path nodes are in scene. You have two approaches to fix that.
First, your path nodes are under a parent object, that parent holds a container script:
public class PathNodes : MonoBehaviour
{
[SerializeField] private Transform m_nodes;
public Transform [] Nodes => m_nodes;
}
Either you use the singleton pattern (yes it is fine when used properly) or have the newly created object use FindObjectOfType then you can access the nodes.
The second solution is to have the prefab of your object to create in the scene as an inactive object. Being in the scene, you can then drag and drop all you need from the scene into it. The prefab is dragged in place of the original project prefab (CapsulePrefab) and when creating a clone of it, you just need to set it active.
Related
I have a homework assigned and I need the make a sound and music volume thing and I want it to be used in other scripts too.
What I mean is :
enter image description here
So when I drag the slider value to 0.2 for example I want the audio source on the other scene to have volume 0.2, but I have no idea how thats made.
Thanks.
(I only have a plan but no code)
Also does anyone know why does it take forever to load when you save a script and go to unity:
enter image description here
A great way to do this is to use static variables that are actually defined for the class And can hold variables between scenes.
public class AudioManager
{
public static float MusicVolume = 1f;
public static float SoundVolume = .5f;
public void SetVolume(float value) => MusicVolume = value;
}
To call them, you just need to write the full name of the class before the variable name.
public class Player : MonoBehaviour
{
public AudioClip AudioClip;
public void Shot()
{
AudioSource.PlayClipAtPoint(AudioClip, transform.position, AudioManager.SoundVolume);
}
}
Remember that these are class variables will set in all instances of the same class. Also if you want your variables to be loaded after re-running the game. I suggest using PlayerPrefs for saving them.
To do this you would write a singleton script AudioManager that is set to DontDestroyOnLoad
It's just a script holding your AudioSources and that doesn't get destroy when you switch scenes.
Something like this
public class AudioManager : MonoBehaviour
{
private static AudioManager instance;
[Header("AudioSources")]
[SerializeField] private AudioSource musicSource;
[SerializeField] private AudioSource soundSource;
private void Awake()
{
// If you have AudioManager in every scene, you want to only keep the main one (the first one)
if (instance != null && instance != this)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(this); // This line will tell Unity to keep this gameobject when switching scenes
}
}
}
Then you can alter your audio sources as you wish, they won't get destroy after switching scene.
Okay Its nice that I have a lot of things to do but okay the script that you guys sent me, so if I put it on the audio Gameobject and I still don't get how I can change parameters from 1 scene to other (I'm a beginner and I'm 13 years old so I might not get what audio ATM's are but yes.)
For short I need this:
Scene1.findgameobject.name = blah blah = audiogameobject in menu
I have a Player script. I have the variables on there
public class Player : MonoBehaviour
{
float horimove;
Rigidbody rb;
public float speed;
public GameObject thrown;
public bool win;
On my other script (I'm making a game where you instantiate spheres into a hole and win.)
public class spheresciprt : MonoBehaviour
{
public Player pscript;
public GameObject player;
// Start is called before the first frame update
void Start()
{
player = GameObject.Find("Player");
pscript = player.GetComponent<Player>();
}
private void OnTriggerEnter(Collider other)
{
if (gameObject.CompareTag("win"))
{
pscript.win = true;
}
}
However pscript.win doesn't change. The bool always stays false but I want the player to win after the sphere hits the trigger in the hole I want it to go to. I tried different computers. The same thing happened in different games I think so I'm probably just missing something.
First of all, make sure that the collision is detected. You can easily do something like
void OnTriggerEnter()
{
Debug.Log("Pass1");
if (gameObject.CompareTag("win"))
{
Debug.Log("Hey, it worked!");
}
}
in the OnTriggerEnter to check that.
If the collision is NOT detected, make sure there are colliders on all the affected GameObjects, as well as a RigidBody component on the sphere. Also, make sure that the collider is marked as Trigger. If you still have an issue with that, we will need to see your inspector to figure it out.
If the collision IS detected... Well, start by making sure that you have assigned the proper tag on the hole. Then, make sure that the player GameObject is actually called "Player" (since you are trying to find it by name) and that it has the script you are trying to get on the object you actually find (and not on one of its children). I hope that works, because I can't see anything else seriously flawed at your code.
Have you tried to change
if (gameObject.CompareTag("win"))
to
if (collider.gameObject.CompareTag("win"))
or just add the rigidbody to both player and other object.
does the other object have "win" tag?
Here is your script:
public class spheresciprt : MonoBehaviour
{
public Player pscript;
public GameObject player;
// Start is called before the first frame update
void Start()
{
player = GameObject.Find("Player");
pscript = player.GetComponent<Player>();
}
private void OnTriggerEnter(Collider other)
{
if (gameObject.CompareTag("win"))
{
pscript.win = true;
}
}
}
It sets pscript to the current values in Player script. This is the problem, because it is setting a variable to the current values, and you want access to the component. You could change this by, just replace all of the pscript variables with player.GetComponent<Player>(). There are other ways of doing this. You could, at the end of OnTriggerEnter, add this:
void OnTriggerEnter(Collider other)
{
...
player.GetComponent<Player>() = pscript;
}
In both of these solutions you fix it. In one, you re-apply the variable. In the other, you are changing the component directly. Which is what you want, because you have pscript as an instance of player script, not the player script that is attached to player.
Currently I am learning both Unity and C#. I am working on a small game where I control a spaceship on the screen, while meteors are spawning in a random position outside of the camera's visible space, then start to move towards the ship.
For this I am trying to refer to the ship game object in a component on a meteor prefab, to get it's position and the angle needed to start moving towards the ship.
public class meteorPath : MonoBehaviour
{
public float speed = 10f;
public Rigidbody2D rb;
public GameObject ship;
void Start()
{
int typeOf = Random.Range(2, 11);
Vector3 posOf = new Vector3(Random.Range(-7f, 7f), Random.Range(16f, 8f), 0);
transform.localScale = new Vector3(typeOf, typeOf, 1);
transform.localPosition = posOf;
}
}
How can I make get the player's position to calculate the angle needed every time I instantiate a meteor?
I'm guessing that you're instantiating everything at runtime.
You would either do:
GameObject.Find(YOUR OBJECT NAME)
GameObject.FindGameObjectWithTag(sometag), only if your player has a tag
Make player's class singleton and reference it from other classes with PlayerClassName.InstanceName and reference the position.
If you're not instantiating everything but is a static scene, then just make a prefab of the meteor with the player's reference inside
one way to get references is to create instanced game manager:
and when meteor is created you have it get player position from that instanced GameManager.
in start of meteor:
private Vector3 playerPosition = GameManager.instance.playerPosition.transform.position;
in GameManager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public GameObject playerPosition;
private void Awake()
{
instance = this;
}
How do I change one or two attribute values of a script so that it effects all the gameObjects that this script is attached to?
For example making attributes SphereSmall and SphereBig global
public Vector3 SphereSmall = new Vector3 (0.001f, 0.001f, 0.001f);
public Vector3 SphereBig = new Vector3 (0.0015f, 0.0015f, 0.0015f);
Two gameObjects has this script attached to and I changed the attribute of public variables SphereSmall and SphereBig on one GameObject. I want this value to be changed in second GameObject as well.
I'm new to unity as well, but here are some solutions:
1) If you're talking about multiple instances of the same object, simply create a prefab out of that object and update the properties of the prefab.
https://docs.unity3d.com/Manual/CreatingPrefabs.html
2) If you're talking about instances of different objects, you can try using the multi-select functionality of the unity editor, this will let you edit all common properties. This is easy if you have lower number if instances and are grouped under a parent object in the Hierarchy pane.
3) If you're talking about instances of different objects and you don't mind seeing the effect of your updates only at run-time: you can try using the ScriptableObject class:
[CreateAssetMenu]
public class CommonObjectProperties : ScriptableObject
{
public Vector3 SphereSmall = new Vector3(1, 0.001f, 0.001f);
public Vector3 SphereBig = new Vector3(0.0015f, 0.0015f, 0.0015f);
}
After you create this script, go to Assets > Create > Common Object Properties:
Now you can use this ScriptableObject instance to add the common values to your objects and after you update them inside the ScriptableObject instance, they will update across all objects.
ObjectScript is the MonoBehaviour script to put on your objects:
public class ObjectScript : MonoBehaviour
{
public CommonObjectPropertis commonProps;
public Vector3 ObjectScriptSmallSphere;
private void Start()
{
ObjectScriptSmallSphere = commonProps.SphereSmall;
}
}
How it should look in the designer:
I'm sure there are plenty of other ways to do this, best of luck!
You could add [ExecuteInEditMode] to your script so it runs while the editor is running. From there you could check if the values are being changed and then update them. Something like this:
[ExecuteInEditMode]
public class MyScript : MonoBehaviour
{
public int myValue;
private int oldValue;
void Update ()
{
if (oldValue != myValue)
{
MyScript[] objects = FindObjectsOfType<MyScript>();
foreach(MyScript myObject in objects)
{
myObject.myValue = myValue
}
oldValue = myValue;
}
}
}
This isn't best practice though so I would recommend looking into using prefab variants instead.
I am trying to get a conveyor belt to reverse its direction when the player presses a button.
Here's the code for the conveyor belt
using UnityEngine;
using System.Collections;
public class Conveyor : MonoBehaviour {
public float speed = 1.0f;
void OnTriggerStay(Collider col)
{
col.transform.position += transform.forward * speed * Time.deltaTime;
}
}
And the code for the button
public class PushButton : MonoBehaviour
{
public GameObject Button;
private Conveyor conveyor;
void Awake ()
{
conveyor = GetComponent<Conveyor>();
}
void OnTriggerStay(Collider entity)
{
if (entity.tag == "Player")
{
if (Input.GetKeyUp(KeyCode.E))
{
conveyor.speed = conveyor.speed * -1;
}
}
}
}
I'm getting an error saying "Object Reference not set to the instance of an object PushButton.OnTriggerStay (Unity Engine.Collider entity) (at Assests/PushButton.cs21)
I'm still not very familiar with using getComponent so I'm not sure how to fix this. Any help would be appreciated.
GetComponent will need a reference to an initialized object and a component or class that object has assigned. For what you are wanting, you will want to find a game object in the scene. Because you are already specifying that your GameObject has a Conveyor class assigned to it, find your GameObject and then specify the Conveyor component.
void Awake ()
{
conveyor = GameObject.FindWithTag("Conveyor").GetComponent<Conveyor>();
}
This should do the trick pending you have tagged your Conveyor game object with a 'Conveyor' tag.
However, there is an even easier way to quickly "grab" something like this. Be careful though!
void Awake()
{
conveyor = Object.FindObjectOfType<Conveyor>();
// ONLY DO THAT IF THERE IS ONLY >>ONE<< OF THE THING!
}
Here's a little essay on that. http://answers.unity3d.com/answers/46285/view.html
You often do that for example to find "boss" objects .. scene managers and the like.
Don't forget though, you can always just use a public variable, and drag inteh Inspector - that's always a sound idea for beginners working with Unity.