#💻┃code-beginner
1 messages · Page 679 of 1
use pivot mode instead of center mode
Okay, so sum up all their positions. Does it result in the value you're seeing in the log?
in a sec
Here is very simple radar script you could utilized to detect enemis just make sure you give the monster tag enemy or just rename the tag to what ever.
using UnityEngine;
public class Radar : MonoBehaviour
{
[SerializeField] Transform playerLocation;
[SerializeField] float detectionRange = 50f;
void Update()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
foreach (GameObject enemy in enemies)
{
float distance = Vector3.Distance(playerLocation.position, enemy.transform.position);
if (distance <= detectionRange)
{
Debug.Log($"Enemy '{enemy.name}' is {distance:F2} units away.");
}
}
}
}
And dont use singeltons for this.
- please don't spoonfeed
- singletons might make sense in this case lol
select the monster and each of its parents and make sure they're what you expect
My guess: The location you're printing is where the monster is. The value you see in the inspector is the local position, which is this object's position relative to the parent
if you debug a instance of MonsterLocation's position. you have a MonsterLocation at that position, full stop. it might not be where you think it is or where it should but the log wont be lying
You're logging global position, which is the position of everything all added together
oh so what do i do then
Do not use and do not suggest using such a heavy function such as findgameobjectswithtag in a update loop please
If what I said is the case, then you don't do anything. The value you're getting is where that object is in the world
i js want the monster pos and player pos distance 💔
still why does it work just fine and as intended when equipped before the round
and doesnt after the round started
💔
Run this code on your player:
Debug.Log($"Player {gameObject.name} is at {transform.position}, Monster {MonsterLocation.instance.gameObject.name} is at {MonsterLocation.instance.transform.position}, and the distance between them is {Vector3.Distance(transform.position, MonsterLocation.instance.transform.position}");
And show what it prints
okay
don't forget you can add the object as context in the second parameter so it is highlighted in the hierarchy when you click the log
Player Radar is at (-89.01, 119.54, -34.58), Monster Bone is at (-89.26, 119.05, -34.35), and the distance between them is 0.5934314
UnityEngine.Debug:Log (object)
Radar:Update () (at Assets/Radar.cs:24)
Okay, so the Radar object is about 60cm from the Bone object.
boiiiiiiii but it works fine if you equip it before the round or aka the monster spawns
Does that track with what you see if you have your handles set to "pivot" and select them each individually in the hierarchy
probably unrelated but is additive scene loading involved here?
whats your networkobject settings for the monsterlocation
Show a screenshot of both Radar and Bone selected in the scene window. The whole unity window, inspector, hierarchy, scene view, etc.
With your handles set up like this:
oh k
mhm?
i do this
void Update(){
if (HasStateAuthority)
{
Body.position = new Vector3(LocalPlayer.instance.Head.position.x, LocalPlayer.instance.Head.position.y + bodyOffset, LocalPlayer.instance.Head.position.z);
if(distanceRotation){
Body.localEulerAngles = new Vector3(xRotation + LocalPlayer.instance.Head.eulerAngles.x, LocalPlayer.instance.Head.eulerAngles.y, 0);//Quaternion.Euler(xRotation + LocalPlayer.instance.Head.eulerAngles.x, LocalPlayer.instance.Head.localEulerAngles.y, LocalPlayer.instance.Head.localEulerAngles.z);
}
Head.rotation = LocalPlayer.instance.Head.rotation;
}
}
in rig player body
to offset the Bone transform
but i dont check for HasStateAuthority
basically each player sets it to themselves?
ima try
oh yeah thats totally what i was checking for
wdym
my lead was a dead end but im glad you found that 😛
(Potentially a reason to avoid using singleons since it being accessible from anywhere means it can be modified anywhere)
My god make a local var for head fuck
Repeating the same access to the instance 5+ times isn't a good idea
But doesn't reloading the scene resets everything and recreate everything, including my GameManager ?
Yes, it does. But since Instance is not null, and Instance is not this, then this object will destroy itself as you've told it to do
How do I make it DDOL ?
Well, the component will destroy itself. The Object will still be around
Hello world !
Sorry if my question is silly : I try to import on my script Cinemachine
The library is well installed with the unity registry, pretty sure of that
I add at the top of my script using Cinemachine; and this is not reconized : Assets/Move.cs(3,7): error CS0246: The type or namespace name 'Cinemachine' could not be found (are you missing a using directive or an assembly reference?)
I try a lot of things : reimport, reimport all, refresh, but nothing worked
Do you have an idea ? (i use Unity 6.1 on Linux Mint 22.1 Cinnamon)
Thx
Are any of your scripts using Assembly Definitions? You might need to add a reference to the cinemachine asmdef to them
have you looked at the cinemachine docs? specifically for the version of cinemachine you are using?
No i don't have one (or i didn't see it ?)
I am on the latest version of Cinemachine, i've didn't take the official docs but i look on the internet and i found nothing (i'll go now on the official docs)
putting it here creates 2 issue. Everything is blue (BG color) when I reload the scene and there's no grid and also I have 2 Game Manager in my hierarchy in the DDOL section
You have two objects named GameManager, but since your script has told the component to remove itself, you only have one GameManager component. You can even see it in your screenshot that this object has no components on it
if you're on the latest ones 3.x+ , the namespace is ~~UnityEngine.Cinemachine ~~ Unity.Cinemachine
https://docs.unity3d.com/Packages/com.unity.cinemachine@3.0/api/index.html
that's also not quite right, but at least they can look at the documentation and see the right answer
you could do Destroy(gameObject) instead of Destroy(this) to delete the entire GO instead of just the component
also, are you perhaps using Start to initialize the board? that's only gonna be called once
Oh ! Nice to know
It didn't fix it rn : Assets/Move.cs(3,19): error CS0234: The type or namespace name 'Cinemachine' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?)
But i think its on a better way, i will dig that
I'm just as lost as you now sorry lol
look 👏 at 👏 the 👏 docs 👏
It's what i mean i will do when i said "But i think its on a better way, i will dig that" you know ? 🤣
it's what you should have already done when i suggested it the first time
You right, sorry dad 🤣
it isn't actually, check again 😉
No joke, i was on the wrong docs, so i didn't find any info about that, and internet is not full of info outside the official doc, but sorry to bother
Yeah dunno. I haven't used Cinemachine 3.x yet so I'm just as lost now lol
check the docs you linked again
Yep, it is Unity.Cinemachine, thx for the help (the doc link will serve a lot !!)
holy hell I'm blind...I'll see myself out 🚶♂️➡️
yeah always check the docs, your eyes work better...
mybad I just woke up and my brain didn't connect lol UnityEngine.something is the usual thing, this new naming threw me off obv.
we will ignore all the helpfull answers you provided from now on
the UnityEngine namespace typically covers things built into the engine while the Unity namespace is typically used for packages
Don't worries! 🤣
I started yesterday and i didn't find the docs you sent first, i was on this one : https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineFreeLook.html
Which doesn't treat scripting at all
tbh my first time ever seeing Unity.something
well that's because you're looking at the manual section rather than the scripting section. and also the wrong version which is why i specified to look at the docs for the version you are using
notice the link said manual not api or sometimes ScriptReference
You click here you get the scripting part
where do I write Destroy(gameObject) ?
in the singleton method you have there
wherever you had Destroy(this) before
@rich adder and do I do the same with Instance = this to Instance = gameObject ?
Hey, how StateMachines work? Or how to do so. I mean cuz im making an enemy and a lot of ppl say their code must need statemachines
there are many ways to implement a state machine. it could be as simple as a bunch of if statements or switch statement with something like an enum to differentiate between states, or something more complex like the animator (which is a state machine). there are dozens, if not hundreds, of tutorials covering how to implement a state machine
How would you store an object of type GameObject in a variable of type GameManager
Oh, but also, why? I mean. What difference is between using functions with Ifs and with using statemachines?
the whole point of Destroy Gameobject is to get rid of the gameobject if one already exist with an Instance assigned for that type
The same difference between having your laundry folded and put in a dresser versus thrown in a pile on the couch
Wich is wich
State machine is dresser drawers
O h
Got it
If i have all system cored and coded into the "silly" (if and function) method, how hard would be to change it into statemachine?
Depends on how you designed it
makes sense
still doesn't work 😕 It's still blue when it reloads 😬
What is supposed to make it not be blue
it wasn't gonna fix that lmao
Oh, so where should I do the Init() of my board and the game ?
anywhere where it'd make sense
When do you want it to happen?
attached to a button, attached to onsceneload, done wherever the actual loading is, etc
Each time a new game starts
So, on scene load?
I don't have a menu, so in this case pressing the game.exe launched the thing directly
yes
It works, thanks 👍 Now however, once I click the grid for the first time after the reload it "reveals" the whole grid but without any value 🤔
How can I make the debugger only step through my scripts and never ever ever go into the engine files?
wdym by "never ever ever go into the engine files"
I only want to see my own scripts, I dont need to see inside the engine
I want to disable this and 'step through' only what I have written.
I believe you want Step Over
unless you mean Continue to hit the next breakpoint without going "Deep"
I need to go through my complete code without ever touching anything that unity provided
im tracking down something horrible, I probably have to make 50+ steps to find it, and I can handle moving 50+ steps through unity code that is not my scripts
if you're stepping manually, you can Step Out of a function or Step Over a function call
can I step out of a class? sorry im new to this type of debugging
you don't step out of classes
debugging, and arguably how code works in general (at a low level) is based on function calls in a stack
each function call creates a new context - that's the context you can step in/out/over
step in to a function call starts debugging each line of that function as it's being called
step over on that same function call skips debugging that function and goes to the next line in the current function
step out stops debugging the current function and goes to the line after the previous function call
im having trouble programming damage dealing upon entering a box collider, each tutorial has the enemies sharing one big script, but mine have separate scripts so that they can have unique stats, how can i program lowering a variable from a collided objects script without the script name of the collided object always being the same
You should probably have a shared parent class that contains all the shared functionality of an enemy
But also, if the only thing that's different is stats, that should probably just be public fields you set in the inspector for the same script
A character having different stats shouldn't require you to make a new script. Maybe show your current setup and !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Make a base script that includes all the shared variables and functions
https://learn.unity.com/tutorial/inheritance
The you cast to this base class and all the others that use it will accept it
anyone please ? 🙂 ☝️
Hi all
having trouble getting this to work
This is firing out of an empty gameobject, which is parented a little outside an enemy
you shouldn't be multiplying your forces by deltaTime, and if that is supposed to be some sort of projectile you wouldn't want the force applied to be time dependent anyway, it should be a FoceMode.Impulse force
but for some reason, the prefab I use (a cube) is not being launched out, instead it becomes stuck
Ok thank you
It is launching out now, but now it's not even going towards the player, but rather in the same direction (to the right in this case)
it's going foward along the world z axis because that is the direction of force you have applied
Oh also why shouldn't I be multiplying by deltaTime? Wouldn't that make the forces run by frame, which is usually better?
Oh wait I meant to apply transform.forward instead
the forcemode you choose will account for time, if one is not specified it uses ForceMode.Force which is time dependent. and this specific force is a one-time force which should not be time dependent
Oh ok
alternatively, if the projectile is already oriented correctly you could leave the current Vector3.Forward and use AddRelativeForce instead which takes the object's rotation into account
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Along with the other suggestions, you can also use a C# Interface to have a damage function that any class can use.
public interface IDamage
{
public void Damage(float amount);
}
And then you can use this interface in any class
//This can be an enemy class
public class AnyClass : MonoBehaviour, IDamage
{
public float health;
public void Damage(float amount)
{
health -= amount;
//You can put anything you want here
}
}
And then to call it from somewhere else:
if (other.transform.TryGetComponent(out IDamage d))
{
d.Damage(damage);
}
If the object has a script thats using IDamage, the Damage function will be called in it. This is personally how I do damage/health in my projects most of the time.
I hope I am not misunderstanding the question, since I don't see anyone else suggesting Interfaces
Hi, for make my enemy current code into an statemachine, do i have to make other script or just use the one i have?
idk cuz i saw two tutorials and in the start they have two different scripts ._.
and seems...complex
this is the unstatemachined code btw
https://paste.mod.gg/wodxpzagsqgq/0
A tool for sharing your source code with the world!
Does this code currently have any problems
i feel like it might be slighty laggy but not main issue
Mostly that i feel that it feels unprofessional or hard to read for myself, complex in a inecessary way, and i encountered multiple problems with animations
If you think it's laggy, use the profiler to check. Complexity could be a problem if you still need to do a lot of work in this script, but if it works and you don't need to touch it you can probably file this under "next time I'll do better"
and i felt that maybe using states would make it more easier to read, to modify and replicate for the other enemies i want to make, help me to understand better code, and fix the animation hierarchy issue.....
the issue is, i have 4 enemies already done who work the same way, and i need to make more enemies, yet this may make it harder to me
and i dont know how to make hierarchy for my anims, cuz they always overlap
So make the new enemies work the new way. Then once you know what you're doing you can go back and change the old ones if they need it
I don't know what you mean by "hierarchy" for animations.
The animator itself is a state machine, it is in one state and has a set of conditions that allow it to move into different states. It's just that the states have animations attached too
i have touched nothing in the animator spiderweb due the same reason i nicknamed it that, too much stuff for my mind @-@
i just use
play.("testEnemyUwu")
what i need is, sometimes two animations play at the same time, i need to set that if two animations play at the same time, only one plays
but thats the thing, atleast for now i dont know the new way
what i do for the other enemies i copy my original enemy script and paste it on a blank script
Don't
huh?
Don't try to do complex animation logic using entirely .play
Use the animator. It's a powerful tool
define complex animation logic
is a 2d sprites game
Anything beyond "Looping an idle pose"
ou
i mean cuz i have to make the enter and the out transitions, set them all to zero, etc
i dont know wich animation should conect to wich
is frustating
So plan it out
Think about what animation is playing, and what needs to happen for it to play something else
like the hierarchy?
No, like the Animator
no but i mean, for make the animator web i should think how i want my animations hierarchy to be
thats it?
two animations plays at the same time
i want the higher rierarchy one to play and shut the lower
Because you aren't using the Animator
Start thinking about what animations can play when, what conditions need to be for it to switch from one to another
i only need the animations to play when patrols, player distance reaches a radious, chases, shoots, hurts and dies
i thought the webs were only for 3D stuff
That's a whole lot more than "looping an idle pose"
So start actually thinking it through.
Start with one state, consider what other animations could be played from that one
and when
idk i just need them to play inside an if, i dont know how to explain it ;-;
also as a side note
it is a bad idea to use animation clips as timers? I mean, instead of using a coroutine
i mean, i make an animation and in a frame i call a function, for make it match with the animation
yes
Animation Events probably, or just use coroutines
sorry i think thats what i meant with animation timers
that instead of using a coroutine i use animation events
Start with a list of all animations you're going to need, then pick one and make a list of all the stuff that animation can transition to, and what needs to happen for that to occur
for example
patrol -> sight -> shooting
any state -> hurt -> dead
Okay, what is the condition to go from patrol to sight
the distance of the player is below an specified float value
So, you'd make an animation parameter that is the distance, and make a transition between patrol and sight that checks if it's less than a given value
Then, in Update, set that parameter to the distance
o h
like a kind of if
but they both are fine
what trouble me is the hurt part for example
it fights with the patrol
hurt must be played when enters the state TakeDamage, to wich the enemy must wait still until the animation wich is less than a sec ends
then don't make a transition from hurt to patrol
no, it's a state machine
like the animator is designed to do
It's in one state. You specify which states it can go to next
i think makes sense
This line if (body.transform.position.y != 0) Debug.LogError($"{body.gameObject.name} position.y is non zero, {body.rigidbody.position}, {body.rigidbody.position.y}");
produces this console message:
And I do not understand it
why is the y coord different between the two?
it's rounded in the Vector3 display
or not rounded, but it only shows the first two digits after the decimal
well, the in game position of the objects matches the vector3, but the inspector shows the y value:
y is 0 for all intents and purposes in game
and in the math its impossible for y to not be 0
Hey @slender nymph do you have a solution for this please ? 🙂
yes, that is an incredibly small value, but it is not exactly equal to 0
never use equality when comparing floats, use Mathf.Approximately if you need to compare them
do not ping people into your questions. and you have surely been here long enough to know that you need to share your code when asking for help.
My bad 😬 https://paste.mod.gg/hpnoucosvqmc/0
A tool for sharing your source code with the world!
I guess im not understanding why its not zero, the gameobject has a Vector3 for position and a Vector3 for velocity with something like body.rigidbody.position += body.velocity * physicsTimestep; and the y is always zero. Is just floating point black magic or is there something else going on?
how have you confirmed that the Y is always 0?
and even if you have confirmed that the Y is always 0, you should still never rely on equality when comparing floats
its a simplified Newtonian 2 body system, where all bodies have 0 on the y axis to start and initial forces are also y = 0. If its so small, I might just clamp it and hope nothing blows up later.
I only did the 0 check because I saw the y value change in the editor, forgeting about floating point math
I have an object pool script (that I wrote from a brackeys tutorial) that I'm trying to work with. The objects that I use that are pooled aren't reused properly though whenever I try to spawn them through the script's method
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using UnityEngine;
public class ObjectPooler : MonoBehaviour
{
[System.Serializable]
public class Pool
{
public string tag;
public GameObject prefab;
public int size;
}
public List<Pool> pools;
public Dictionary<string, Queue<GameObject>> poolDictionary;
#region Singleton
public static ObjectPooler instance;
void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
Destroy(gameObject);
}
#endregion
void Start()
{
poolDictionary = new Dictionary<string, Queue<GameObject>>();
foreach (Pool pool in pools)
{
Queue<GameObject> objectPool = new Queue<GameObject>();
for (int i = 0; i < pool.size; i++)
{
GameObject prefab = Instantiate(pool.prefab);
prefab.SetActive(false);
objectPool.Enqueue(prefab);
}
poolDictionary.Add(pool.tag, objectPool);
}
}
public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
{
if (!poolDictionary.ContainsKey(tag))
{
throw new System.NullReferenceException("The referenced tag " + tag + "does not exist" );
}
GameObject objToSpawn = poolDictionary[tag].Dequeue();
objToSpawn.SetActive(true);
objToSpawn.transform.position = position;
objToSpawn.transform.rotation = rotation;
//Remove this with OnEnable later
IPoolable pooledObj = objToSpawn.GetComponent<IPoolable>();
if (pooledObj != null)
{
pooledObj.OnObjectSpawn();
}
poolDictionary[tag].Enqueue(objToSpawn);
return objToSpawn;
}
}
what do mean when you say properly re-used?
alr let me explain that in a second
i'm curious why you immediately enqueue the object back into the pool as soon as you get it?
also is there a reason you've followed a tutorial to write your own object pool instead of using unity's built in objectpool class?
so, if I set a maximum size for the pool, such as 5, there can only be 5 instances of that object that are continuously reused, that works. But whenever those objects are reused, they are not properly set at the position or rotation specified, and their events that should run on onEnable time do not run
well what does the OnObjectSpawn method for those objects do?
and by that i mean, please show the actual code and do not just provide a vague description of what you assume the code is doing (clarifying because too many times i've had that happen)
oh i was not aware that unity had a built in object pool class...
it's had it since 2021
Alr
first is the method from the class and the second is the case of usage
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
lemme get smth else
but again, we need to see the OnObjectSpawn method
yea that
The onEnable method just does this
it calls a seuqnces of tweens to animate the object
- #💻┃code-beginner message
- still need to see that OnObjectSpawn method
- i imagine that you probably want those sequences to start after you've set the position and rotation, so consider setting the object active after assigning those properties
so far, I'm going over the API for the built in object pool class, I think that might help me more if this doesn't work out
Which namespaces and classes I should have to learn first to create a basic 3D game?
that's a nonsensical question. you should learn how to use c# then learn the basics of just using the engine. you won't be learning specific "namespaces and classes", you'll be learning how to use the unity API.
also unity has some materials you can !learn from
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
there are beginner c# courses pinned in this channel and the pathways on the unity learn site will teach you how to use the engine
does anyone know by chance how to write in collision between two spheres if im coding a 2d playformer with pygame
this is a unity server, perhaps go find a pygame related server and ask there
i cant find one lol, thanks tho
also don't crosspost
Yeah. I mean, it is unjty server. But you could search for the ABAB method, for box, for sphere, get distance. Like, a spehere is just showing the distance.
If it is in distance, than you can be sure, it collided.
hii
whats the best unity editor version for my non gpu ryzen 5 5600GT build? i just want to make 3d simulator game for android
this is a code channel. and the "best" is whichever version meets your needs and you can actually run.
you can view the system requirements here: https://docs.unity3d.com/6000.1/Documentation/Manual/system-requirements.html
and just change the version in the upper left if you want to check different versions
For starters #🔎┃find-a-channel
If you can't find an appropriate channel try asking in #💻┃unity-talk
is there any help channnel
ok
How with this code in the code https://paste.mod.gg/jhlpgdozxjze/0 I keep sometimes getting a -1 tile on my first click please ? 🤔
private void OnMouseDown()
{
if (GameManager.GameOver) return;
if (Revealed) return;
// Make the first tile never be a mine
if (!firstClick) {
print("firstClick");
firstClick = true;
if (Value == -1) {
print("firstClick && Value == -1");
Value = 0;
}
OnFirstTileClicked?.Invoke();
}
RevealTile();
}
A tool for sharing your source code with the world!
because it checks the tile's value before it has generated the mine locations
hey, how i can make an static script? I mean cuz i want to keep the life and other values of my player from scene to scene, and my plan is to send those values to a referenced static script, the thing now is. How
You probably want singleton manager class that's marked as dontdestroyonload
oh, but i have to make it an object in the scene?
You don't have to, you can mark a class as completely static, but generally it's preferable to use a live instance for various benefits (being able to inspect it's properties, running coroutines etc.)
oh, makes sense
your also free to make a majority of it's usage static aswell (eg. its public functions and all that) where the code inside of them might point to the instance if necessary
there is also this method https://docs.unity3d.com/6000.1/Documentation/ScriptReference/SceneManagement.SceneManager.MoveGameObjectToScene.html or just putting the player in DDOL. The only downside would be having to manually destroy the character later
static itself here isnt required depending how u want to set it up. you likely have some script responsible for scene changes. around that logic is where you could copy values you want from the player, spawn a new player in the new scene, write the values.
lots of options
thanks :3
DDOL?
dontdestroyonload
oh
Screenshot from a tutorial, I didn't quite understand the point of interface.
He said it's a contract for all weapons to require those methods, but doesn't the abstract class itself already do that?
the short answer is yes
the longer answer is that having the interface be the bottom foundation rather than the abstract class in a lot of cases is more flexible because your don't need to define it's class (eg. base, monobehaviour, scriptableobject) and that in a lot of cases you may want completely different "trees" of inheritance both spanning off the same base interface, or even having that interface come into play in the middle of the inheritence tree etc.
Based exclusively off that screenshot it's not the best example for why you would want a seperate interface for IWeapon but imagine if you instead had a IDamageSource interface, where that might be used on your weapons, environmental props, global things etc.
Same with the fact that it's equipable
Yes
But it really depends on a lot of things
The easy answer here is that your abstract class is very likely to be enough. Anything using the IWeapon inferface likely uses the abstract class.
The point is that IWeapon is a small contract indicating a specific feature, whereas an abstract class is somewhat the same, but also allow for implementation of that feature (like reusable code between weapons)
generally you'd use a base class when there is shared functionality, and the child class "is a" base class. So a sword is a weapon - and all weapons have a sprite and display that sprite in the ui when they are equipped
interfaces are more about describing what something does. They are really good when you want a bunch of different things to have a common set of methods. In this case, maybe you've got a fireball, which inherits from SpellBase - but it's not a weapon, and doesn't need to do the same things as a weapon. However, it can still be equipped and used!
An interface is commonly used for specific features which a class needs to implement. A good example is IDamageable, which would implement a Damage method. I can then check if this interface is implemented using pattern matching, and damage the given object.
Another important note, a class can have multiple interfaces, but only inherit from one abstract class. The latter is likely solvable with composition.
So for this you likely end up needing a WeaponBase class which inherits from MonoBehaviour instead of an interface. However, it also depends on if you have any explicit code that weapons might use which would be reusable between weapons. You could perhaps even put these in separate static classes if they don't work with an instance.
If not, then an interface is just a lot easier. Your player likely just checks for this interface, then from there call one of its methods.
Okay, thanks 👍
Bruh why did I learn only just now about static event System.Action<T>, this shits so useful
I have been using UnityEvents but they're not that good if you need to pass any arguments
🤔
UnityEvents allow you to pass arguments
Depending on your use case you can use Action, Func, EventHandler or UnityEvent. The only difference is that UnityEvent is not technically a delegate I believe
But UnityEvent does get serialized and can be used in the inspector
Oh they do huh, ok mb
That's the only reason to use UnityEvent really
It's useful to learn about these things though, it's a good thing you figured out these exist 😄
the built in listener null check too ig but minimal
I don't know what that means
You would if the Unity event was null
yeah but doesnt System.Action throw if its not null but has no listeners?
Yeah I can definitely see a major improvement in my code in the span of 1 year even when I had million hard coded references to other classes everywhere
saving typing a ? isn't all that much really 😄
I guess it's more that if you forget it for some reason, it won't throw an error?
is it ever null if it's serialized?
Generally wouldn't be but that's besides the point
someone in here a week or two ago was destroying them as a way to only run them once
so you never know 😄
(yeah im just asking a separate question)
UnityEvent inherits Object?
I forget whether an empty delegate is actually null, I've never properly looked into how they're implemented
delegates are ref types right 
Yes
Anyone please ? ☝️
So the issue is RevealTile(); or OnFirstTileClicked?.Invoke();that's in the wrong place ?
UnityEvent should not be null if serialized by unity.
delegate events can be null if there are 0 subscribers
hence why people do the ol event?.Invoke()
OnFirstTileClicked?.Invoke(); is what triggers placing the mines into the grid. You can't check if there's a mine on the tile if you haven't placed any mines yet
Thank you 👍
something weird about this tutorial
first this is not advanced im still a very beginner and this piece of code is for moving left and right in a 2d platforming
Now with the exact piece of code showing in the ss, the OP could move the character left and right what confuse me is there's no code line like "Input.GetKey" or "KeyCode.D"
I used to understand the code before I smash it into my VS sooo I wanna understand this
Note; I know in Unity 6 it's "LinearVelocity" not "velocity" our dude clarified it in the comments
Input.GetAxis("Horizontal") returns a value between -1 and 1
if you're holding down a key to the left, like the A key, it returns -1
if you're holding down a key to the right, like the D key, it returns +1
But how can the engine know that the button I need to press to return the value -1 is A?
it's a defined thing in unity
Alriiiiiiiight
Thx mate ^^
"The meaning of this value depends on the type of input control, for example with a joystick's horizontal axis a value of 1 means the stick is pushed all the way to the right and a value of -1 means it's all the way to the left; a value of 0 means the joystick is in its neutral position." - unity docs
conversely, if you use the Vertical axis, it's gonna listen for the W and S keys
this also applies actually to the arrow keys
so if you try that code and hold down either the left or right arrow key it should still work
though for good practice you should use the new input system, there are a lot of videos online regarding it
I see that Unity does thing by its own with no need to code it by the user Oh that's why it's called game engine
Anyways thanks for your explaination
also! there's this 10 hour course on youtube, for free. Teaches you a lot of the basics and even some intermediate stuff. I suggest once you watch that course, you try to rely on your own programming so that you don't end up in tutorial helll
learn how to read the docs
Alright what's the name of this course or the yt channel? + Are these docs available in Unity's home page?
Because it's set in the Input Manager in player settings
then the course is from CodeMonkey
it's project based which I really like
"Horizontal" is one of the default axes already set up
💬 This was a ton of work to make so I really hope it helps you in your game dev journey! Hit the Like button!
🌍 Course Website with Downloadable Assets, FAQ, Related Videos https://cmonkey.co/freecourse
❤ Follow-up FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
🎮 Play the game on Steam! https://cmonkey.co...
You can change or define more in the input manager window
Alright one last question
you know any tutorial specified for 2D animations on Unity?
I know the art itself is out of Unity I wanna do the animation itself in Unity
I'm not very familiar with 2d in unity but I believe you're gonna have to just make a spritesheet outside of unity
There are two different kinds of 2D animation basically, spritesheets and skeletal
You'll need to decide which one you want to use first then find a tutorial
Which one is better for pixel art/simple shapes?
you can't use skeletal animation with pixel art
well ok you technically can but it would look terrible and it definitely wouldn't be pixel art
can anyone help me out? why is my tool not working how it should?
seems that toolScript is null
if you want to share code, do so as shown below, not as a video
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i just added a null check and yeah, but why?
give me a second
that doesn't solve the issue, that just silences it
find out why it's null and make it not null
Player Controller - https://pastebin.com/iYnrp7cg
Tool - https://pastebin.com/Jh2JyZMq
Weapon - https://pastebin.com/6FkRFUCt
EquipableItem - https://pastebin.com/HEdAh31Z
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the way i have it setup on the scene is, the tool script is on the tool prefab itself, weapon follows the same logic (but I havent tackled that one just yet), the tool prefab is inside of an empty object called "ToolsVM" and it's inside the main camera
(VM being viewmodel just for clarification)
Is there an equivalent to "OnMouseDown" but for right click please ?
i believe its
KeyCode.Mouse1;
That's not my question 🙂
I don't think the function exists, but to achieve this, you can use the OnMouseOver function and then check if the right button is inputed with GetMouseButton(1)
Check this forum on this, someone made a video and there are even more workarounds if you need
Thank you 🙏
Wouldn't it be easier to just use GetMouseButtonDown or GetMouseButton?
In Update yeah it also works
you simply never assign to toolScript, it can't possibly have a value
yep, i did it and it works now, however, how do I assign multiple prefabs with the same script? there will only be 1 active in the moment
i have no idea what you're referring to
i don't know what the context of your game is
assign to what?
i'll have multiple tools, how can I assign these to multiple prefabs?
Select them all, the inspector will show any shared components between all selected objects. Then you can drag something in to all of them at once
so i can just select all the prefabs with the script onto that field and it'll know???
you have multiple tools and you want to assign all the tools into a single slot?
yes because they all have the same tool script
it's a single slot, you can't have multiple tools in the single tool slot
thats exactly the problem
use an array or a list if you want to have multiple tools
Both can work, look up what they are to understand.
If you select multiple things that have the same script, the inspector will show all shared components of all of the selected things. Then you can assign them all at once
i dont follow
So, you have a script that has a variable ToolScript and you want to assign a Tool to a bunch of them at once, is that right?
yes, i want to assign the tool.cs (toolscript) onto all of my tools
So you would select all of the objects that have the variable you want to assign, then drag in the Tool you want them to reference
^^^??
The thing you're telling them you want to do and the thing you're telling me you want to do are different things
no it aint
So you're getting two different answers because you've asked two different questions
when did I ever ask two questions?
Here you say "I want to assign the same tool to multiple scripts that reference them" which is what I answered.
@polar acorn they asked a single ambiguous question and you answered without asking for clarification lol
Here you are saying "I want this one ToolScript to reference multiple different Tools" which is what Chris answered
ah, nvm. that's pretty clear-cut
These are two different situations
I answered the question they asked, and if they wanted to ask a different one they should have asked that one
yall are confusing this for no reason, i was still talking about this
Yes, because that's the answer to the question you asked them. I gave you the answer to the one you asked me
forget it because its not what i meant to ask
Because we each assumed a different thing you were doing, gave an example of it, and you said "Yes I want that one"
So how about instead, you say what you actually want to do
and then we can start from zero on the actual question
im going to ask again
how can I assign multiple objects with the same script on the player controller to avoid the null?
a list or a array, what would be the difference in my case?
how you interact with them
Which nulls btw?
What do you mean "avoid the null", you have a value assigned. It's not null
avoid the null on tools that are not assigned
its not nulling now because i have the tool i want assigned, but when I add another, how am meant to
i answered @ivory bobcat 's question to the context
you have tools that aren't assigned to that slot.
the issue is when there isn't anything assigned to that slot
So assign a value to those
how???? its a single slot script
A list and swap out what your primary tool is?
then make it multiple slots with a list or an array
i asked what was the difference between a list and a array
which i still dont know in this context
Dear lord I see multiplayer components here too.
@oak mountain you aren't being precise in your statements - "assign" isn't a valid action on its own, you assign to something
a list grows dynamically
an array doesn't, it's fixed size
sounds like you need to step back and go through some c# fundamentals?
you're lacking the understanding to properly explain the issue or understand our answers
its almost as if we're in the beginner chat
You can very easily Google this. This is really a basic of c# though. Especially since youre trying multiplayer, I'm sure most people here would suggest taking a step back
i knew what an array was, but i didnt think it had that difference
im not implementing multiplayer, my friend is though
Beginner of game development
and what is this that we're doing?
What, multiplayer? Why are we in the beginner chat then?
Telling you that array vs list is a c# basic
because i didnt ask a multiplayer related question??
i knew what an array was because i used it myself for my barricade script, but i didnt know list existed, i thought arrays were the only listing way
There are multiple types of collections , which is what you're referring to.
Lists and arrays are just two.
gotcha
i dont have the terminology fully down yet, apologies
So then it's assigned. It's not null. What is it that you want to do? You want to avoid the null reference exception - you've done that. If you add another copy of this script somewhere, assign a Tool to that.
The basics to what you'd be solving here is really any collection of Tools. Then you swap out what your active tool is
but that isnt pratical at all
Why not? How many PlayerController scripts do you intend to have?
we know and expect askers in this chat to not fully understand what they're doing - that's what a beginner is
the problem i'm referring to is that you're getting in too deep for yourself right now, and your issues are at a higher level than your understanding
1 only, for the player prefab
So then you're good. No more null references ever
You've assigned a value to the variable. It is not null.
well yeah but then i'll never learn if I dont leave the comfort zone
I'm fairly certain they're thinking about this in the opposite way. Instead of null, its just nothing is referencing those other tools that may exist on the same GO as the player.
Unless I'm misunderstanding here
you're too far out of your comfort zone, you can't even properly explain what you're trying to do right now lol
step back and think about the design first
I'm trying to get them to actually explain what they intend to do by answering the questions that are actually asked until eventually we're left with the intended one as the last one left standing
if I have 3 tools on my player (only 1 is active always) and assing a tool in the player controller to fetch it's tool script, it'll only execute actions from that one assigned tool, regardless if I change the active tool
Fair though I just didnt think it'd really get there
Okay, so, you'd change which Tool script that variable points to.
is this the issue or the goal
When do you want that to happen?
shit i get it now, i was trying to assign every tool onto the list, and since only 1 game object (tool) would be active, it would just fetch the only active one because how can it execute OnPrimaryAction() on tools that arent even active on the hierarchy?
does it make sense?
i think both end up going for the same goal no?
So, you would want a variable that holds the current tool. There are many ways to change which tool is active, so you'll need to think about when and how that change happens
You'd just change which Tool script that variable holds
my idea for the inventory is kinda like how the forest handles, where you assign items to quick slots from the inventory
so if I assign my tool for slot 1, when i press 1, it'll activate the game object that matches what i assigned in the inventory's quick slot and disable every other object
and since every prefab has the tool.cs, but the player controller is the script that controls the inputs, how can it control inputs of prefabs that aren't even active in the scene? thats why i wanted every tool to be assigned in the playercontroller's tool.cs field
Whenever that happens, you'd need to change which Tool this script is referring to. That means something involved in this process is going to need a reference to the Tool in that slot, and pass it to the player
so you're saying that its best to assign which tool the script is referring to through the quick slots?
what diferences a statemachine with a behaviour tree, and wich one is better for enemy ai?
they're pretty similar structures
there is no "better" both have different purposes
but what diference they have?
i mean, i already made four enemies with the if + function method but i dont like how i write them, so im seeking a way to convert them into a more profesional readable script
Have you searched what either of them do?
you should probably
then
most cases you will get away with a simple statemachine
makes sense
How does that suddenly make sense? lol
You asked a question that nobody has yet deep dove into (for good reason, it's a big topic) and now it makes sense. 🤔
https://www.polymathrobotics.com/blog/state-machines-vs-behavior-trees
Try reading through this.
i meant the idea of searching it on my own... sorry
So I have a problem. If My player triggers the warppoint it warps back and forth without break. I have this Code for the warppoint ```cs
[RequireComponent(typeof(Collider2D))]
public class Passage : MonoBehaviour
{
public Transform connection;
private void OnTriggerEnter2D(Collider2D other)
{
Vector3 position = other.transform.position;
position.x = this.connection.position.x;
position.y = this.connection.position.y;
other.transform.position = position;}}
I have all these errors and I don't understand where it comes from knowing that it doesn't give a script name nor a line where I can check 🤔 Could anyone tell me what could the issue be please ? https://paste.mod.gg/fjslcyeiaebl/0
A tool for sharing your source code with the world!
editor bug looks like
try restarting unity
when the namespace is UnityEditor in most cases its not your code per-se
Basically, if the place throwing the error is some gibberish mashup of numbers and letters instead of a script name and line number, it's internal
Hi, btw
what diference is using a timer (substracting a value using Delta.Time) or a Coroutine? wich one's better?
Using a manual timer by accumulating/subtracting time gives you more control. You can pause it, slow it down, speed it up, or modify it at any point.
o h, interesting
coroutines is more like when i want something to happens after something, right?
like, i want to shot 3 bullets consecutive, a timer may do the trick but may be too elaborated
They're powerful for sequencing things, yes.
They both use time, since you can yield to time in a coroutine.
it starts unity project like unreal and doesnt have any highlighting
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
how can I apply force to a 2d object from a specific point, instead of just perfectly along the center of mass?
I'm trying to acheive a 2d driving model that "feels" nice and weighty and "real" without going so far as trying to do real tire physics which would be a big scope increase
I have an issue. For some reason when I click on a tile that's zero (the tile with no number), it shouldn't be a zero tile if it has mine(s) next to it like in this screenshot example you can see in the second screenshot that I clicked on a mine that's next to the zero tile, so it's shouldn't be "0" by any mean but it's the case and I don't understand why 🤔 https://paste.mod.gg/vzhnlratqmtw/0
A tool for sharing your source code with the world!
oh, that looks like it'd work perfectly, I don't know why I thought to google tire solutions but not that specific thing lol. I feel a bit silly, oops.
looks like a perfect solution, I can use it to push the car sideways at the front axle
I think I solved it 👍
if I have a tank I'd like to define, and I'd like to split the functionality into multiple scripts for readability, what would be the best way to structure that?
Ideall I'd like to be able to call Tank.setControls([control state data])
and Tank.fireGun()
but have setControls() and fireGun() in two scripts, one that handles driving physics and one that handles weaponry
Is that acheivable, or will I always need to call it like Tank.Controls.setControls()
and Tank.Weapon.fireGun()
both are pretty valid, its mainly what you would find easier. I'd probably pick option 2
im sorry, but i dont know what this error means, i dont remember switching anything called input handling, i dont know how to fix that, the video i found show a different situation that isnt mine
I'd keep the scripts (functionality) separate. Makes it easier to debug and add/remove when building the object . . .
im trying to set the player movement following a tutorial
unity 6.1 defaults to using the Input System for the active input handling. if you are following a tutorial that uses the old input manager then you need to follow the instructions in the error message to switch it to either Input Manager or Both
By default, Unity uses the new input system, but your code uses the old input system. You just need to change the Input Handling in the Player Settings, that's all . . .
that statement just injected a flood of ideas into my head about adding and removing them from specific vehicles to make a mix and match vehicle creator that will actually work really well with my existing work and framework
im not sure whether to thank or curse you
because I can't not do it now
just unsure whether I'll make it a game mechanic or keep it just a dev tool
why not bolf?
there is no create action, what i do ?
it's not there because you already have an input action asset assigned
what
what was not clear about what i said?
when was a input action asset assigned, the one that is outdated?
Ooo, I could split every vehicle into a locomotion type and a turret type, and then have smaller addon modules
The control script for addons can just be tweaked a little to send universalized inputs, so it goes from like, scanner.activate()
To just utilityslot4.activate() and make sure every utility script has an .activate() function
you already have one assigned. compare the two screenshots, but ignore the circled bit
this is why people should be using the same editor and package versions as the course(s) they follow because little changes like this when you have 0 idea what you are doing and don't know enough to actually look at your own screen make following the courses difficult
its hard to find something you want the way you want on the version you want man
should i delete the default one and make another? because the guide has this block of text which i have no idea how to follow when the thing is already created
should it be important?
i dont know
because unity's tutorial isnt following the same logic as my recently created project
follow a structured course to learn what you are doing first, then when you already know what you are doing you can go and make what you want.
that way you aren't trying to find all these hyper specific things and then just flailing along blindly when you cannot find the exact right thing.
im following the structured course of unity on how to use this thing, and it isnt really helping much as every outcome is different
on a file i created today
or unity is outdated?
if you are following a structured course, then use the same version that the course teaches.
well
then unity is outdated on their own tutorials then
i will try finding out what to do
is this even from an actual course? or is this a snippet from the documentation page for a specific version of the input system package?
!IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
VS still doesnt have any intellisense after I reinstalled it. Using latest unity and VS versions
It worked normally for anything else. I also went back and installed docs for the unity version I was using. Still no intellisense
installing docs doesn't do anything for configuration
make sure you've actually done all the steps mentioned, not just reinstalling
all of what is in this site tells me to set parameters that were already set by default and check updates that are already installed because i installed latest versions 5min ago
did you go through the troubleshooting steps in the link that i sent
yes, i am going trough a different link now and its starting to work, i am restarting solution explorer solutions with dependecies
Is it possible to make it not say 0 references when the engine is referencing it with the movement component and starting it
what do you mean by "it"?
well i mean yeah they aren't referenced
I am using it inside the editor
thats why it says 1 asset reference
the other ones get called by unity (they are messages like events so they get invoked by unity by method name)
is there a way to make OnMove not grayed out (no color filter)
the 0 references refers specifically to your code. you are not using that method in your own code so it shows that
there is no way for visual studio to know that is called magically by the PlayerInput component
make it public/protected/internal or disable the feature altogether or configure On* methods to not do that
thanks
(don't know how you could configure that, but i mean. it might be a thing. idk.)
Use Generate C# class and opt for actual events 
Hi, I'm following the Unity Essentials Pathway and I've just got to the point where it teaches me how to code. It said that if the script doesn't open in an IDE I should reinstall Visual Studio, do i have the IDE?
yes, that's visual studio
Ohhh right
By the way
I noticed that the guy from the tutorial has this at the left side, which is the Unity Project folders. They dont show up for me in the Visual Studio, how can I enable this?
that is another IDE
Oh so it's not Visual Studio
They are using vs code, your are using visual studio (it's better)
it is not always about good looking
no, they're just separate apps
I see
at bottom press on Explorado de soloution
this is what it shows
you can expand the hierarchy but you already have your open scripts at top anyways. do not care about that too much
Ohh its true, thanks!!!
is there a way to use spritesheets outside of using them for looping animations?
specifically I made a spritesheet with a number counter, and one blurred "spinning" sprite to be an inbetween frame
I'd like to be able to call changeNumber(4) and the renderer displays the spinning sprite for a few milliseconds, then shows frame 4
I could just seperate the sprites out and make them selectively visible but that feels too hacky, and my googling efforts mostly find me tutorials about transitions from and between loops
are you using the actual animations systems for those at all? or just doing manual sprite swapping?
neither yet, trying to figure out which to use
I have the sprites in the form of a sprite sheet I exported from Aseprite
and it's sliced correctly
if you want to make an actual spinning animation and/or have each number have idle animations, you could use an animator now to give that flexibility for the future
but if not you could just have an array of those numbered sprites and a specific slot for that intermediate sprite and swap between them manually
fyi with aseprite you don't need to export, unity can import ase files directly
I did do that, yeah I was glad to learn that!
so just, have a script that holds an array of 11 sprites (0-9, blur)
and then use something like spriteRenderer.sprite = sprites[4]
you wouldn't have the blur sprite in the array, you would use it separately
the blur isn't the 10th number
Download Rider, it's way better (and it's free) 🙂
So, in the past, when I needed to make an action take a specific amount of time, I always just did something like
FixedUpdate()
{
timeSinceThingStarted += 1
if (timeSinceThingStarted > amountOfTime && doingTheThing == true)
{
doTheThing()
doingTheThing = false
timeSinceThingStarted = 0
}
}
I never thought to ask, is there a better way? Some
doTheThingInAWhile(function(), time);
- they're all free
- whether each one is "better" than the others is quite subjective
- getting any ide is good enough for a beginner tbh
you could use a coroutine that takes in an Action and a time and just WaitForSeconds then invoke the action
there is InvokeRepeating, but "better" is kinda complicated, and InvokeRepeating is typically not regarded as better since you don't get any control and you have to use a magic string
is the thing to do important? like DoT or something
if so, keeping time yourself is typically better, so you can make up for lost time between frames
- imo Visual Studio looks so heavy / overloaded in terms of interface and loading, to me it looks like the worst IDE in existance 😬 I really like Visual Studio Code but I don't know if it needs alot of setup for Unity.
in this specific instance, I just want to flash the blurred sprite for a few milliseconds, then show the updated number
looking for a solutionfor small, mostly unimportant visual stuff like that where getting granular about it feels like overkill but I don't know a better way
you tend to get this sort of pattern for important stuff:```cs
/* some update loop / {
float elapsed = 0;
while (true) {
elapsed += Time.deltaTime;
while (elapsed >= timeInterval) {
/ do thing */
elapsed -= timeInterval;
}
yield return null;
}
}
coroutine it is!
Imo coroutines are the nicest in most cases purely because it’s an excuse to move that logic into a dedicated function
I'd like something like
updateNumber(int number)
{
sprite = blur;
wait(30);
sprite = numbersArr[number];
}
I'll look into coroutines
Yeah coroutines are literally that lol
private SpriteRenderer spriteRenderer;
private Sprite sprite;
spriteRenderer = GetComponent<SpriteRenderer>();
sprite = spriteRenderer.sprite;
Why does this not make sprite a reference to the component I can use to change the sprite?
If I made it sprite = GetComponent<SpriteRenderer>().sprite; it would if I understand correctly, why does it not in this case?
why do you expect it to do so?
sprite isn't the component, it's just the current sprite of the component
(Aka it’s the photo and spriterenderer is the photo frame)
I was expecting sprite to be a pointer to the property of the componenet, but now that I'm saying it out loud I don't remember where I got the concept that it would stick like that
it might be leftover from visual basic from forever ago crossing a wire in my head
c# typically doesn't use pointers or references in that way
Yeah setting via getting like that gets you the value inside the box, not the box itself
idk visual basic, but sounds like what you're thinking of would be something like this in c/c++ terms
spriteRenderer = GetComponent<SpriteRenderer>();
Sprite *sprite = &spriteRenderer.sprite;
// or
Sprite &sprite = spriteRenderer.sprite;
which c# just doesn't really do
but in my example isn't spriteRenderer a pointer to the actual SpriteRenderer? changing it to be something like
foo = GetComponent<SpriteRenderer>();
would make foo a pointer to the component in the same way, would it not?
it's a reference, but yes same idea
the thing is, getting the sprite gives a reference to the actual sprite, not the spriteRenderer's property that holds said sprite
I think I see
Can I only make references to components, and not properties unless the property is itself a component?
no, references don't care about components
this is a c# thing, not a unity thing
imagine something like this:
Vector3 pos = transform.position;
```changing `pos` wouldn't affect the transform's actual position, right?
now that's a value type - changing the pos changes the actual underlying value
that value isn't linked to transform.position at all
but it goes a little differently with a reference type, because now there's 2 ways to change it - do you mean mutating it, or replacing it altogether?
in your scenario, sprite is a reference to some Sprite in memory
that's not directly linked to the spriteRenderer.sprite, they just happen to point to the same Sprite - that's what getting the reference is
so now if you change the actual Sprite that sprite points to, ie mutation, like sprite.pivot = new Vector2(0, 0);, that change propagates to spriteRenderer.sprite because it points to the same Sprite
but if you change sprite, as in the variable, like sprite = myOtherSprite;, that's reassignment - there was an indirect link to spriteRenderer.sprite via the underling reference, but not the actual sprite variable
so that doesn't affect spriteRenderer.sprite
microsoft have their own explanation for how reference types and value types work: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types
Hey all, I have a question on object references. I was watching Tarodev's video on Object Referencing here: https://www.youtube.com/watch?v=dtv7mjj_iog&t=761s
I am unable to replicate what he is doing at the time stamp. Basically instead of using:
[SerializedField] private GameObject myGameObjectPrefab;
private GameObject _myGameObject;
private _myScript myScriptFromGameObject;
and then setting the private member via _myGameObject = Instantiant(myGameObjectPrefab);
AND then relying on _myScriptFromGameObject = _myGameObject.GetComponent<myScript>();
He is able to set the prefab serialized field from GameObject type to the prefab as a type, and also set the private member variable for the instantiated GameObject to the prefab type as well?
I am not able to get rider to accept this?
PSA: The "Unit" class is a simple class I created to represent a unit in my game. It's NOT an inbuilt class. Sorry for the confusion.
As a new dev, keeping references to game objects you need can be a little confusing. Learn how to store game objects for later use as well as allowing external scripts access to your goodies.
Instead of trying ...
Yes, so in my case the prefab is called Player, I cannot switch the serialized field or private variable to the prefab type
why
he demonstrates in this, that if you do that you dont need to do GetComponent
why can you not switch the serialize field or private variable to the prefab type
Rider says its wrong
what does it say
note that it isn't the prefab type, but rather a type of component that is on the prefab
You do not have a class (and therefor Type) called Player
okay thats what I thought, although this video is starting to become more mysterious, maybe because his naming
presumably you want your prefab variable's type to be PlayerManager
The prefab he supplies to his serialized field is fully instantiated
doesn't matter
so you can make a gameobject's type one of its components?
you can drag a gameobject into a slot in the inspector for a variable that is of one of its components type
It's still a GameObject type instance that has multiple MonoBehaviour type instances on it as components, this just lets you be more specific/direct about what your doing
hmm, yeah i dont know if i like this route, would you suggest i stick with the regular GameObject type for the serialized field and get my components as needed?
using the actual type you care about instead of GameObject is 100% better in all cases
okay, thank you, appreciate the quick help
So in this case, what id like this script to do (among other things but ill figure those out), is look at the serialized field for a prefab, spawn that prefab, and then get another script component from that spawned prefab. Is using PlayerManager type instead of GameObject still the way?
if the prefab has a PlayerManager component on it, and that is the type of object you want to get from the instantiated object. then yes, your prefab variable should be a PlayerManager type, then you can directly assign the other variable the returned object from Instantiate with no need to call GetComponent
Because Unity enforces that
Every GameObject has a Transform
Every Transform has a GameObject
Anything deriving from MonoBehaviour has a GameObject (and therefore Transform). You can easily jump between these references. In some cases Unity builds in some of these functions to simplify their use too
okay, understood, if i had a second script on PlayerPrefab (Lets say PlayerSkills), that was not PlayerManager in this instance I would need to GetComponent<PlayerSkills>() to get that additional one in this situation?
sure, or you might have a direct reference from PlayerManager depending on how it's set up
that was not PlayerManager in this instance
a MonoBehaviour class / component cant be on another component
components live on gameobjects
it's kinda comparable to components being employees inside a store (gameobject)
If you walk into a grocery store, you don't know who all the employees in the building are
but if you walk up to an employee, you certainly know what store they work at
Yeah makes total sense, i think if anything I was thinking a bit too much on what I was seeing.
Question on Timelines:
In unreal, id often animate shader parameters and objects via sequencer (timeline basically).
In unity, ive historically done this via async tasks to drive shader parameters.
Async tasks, even when driven by curves and what not, tend to be difficult to dial artistically, where timeline allows for really nice sequencing and lookdev.
Is there some bad performance implication from using timelines vs Async Task tweening(my target platform is mobile VR)?
Timeline is just a collection of animations/animators, etc. It's no different than if you used those instead.
So no, there isn't any major performance difference than doing it in code (unless you're animating UI elements, which is a bit of a consideration if you're not breaking your canvases up properly).
I love chat GPT, it gave me working player movement script🥹
just wait until you find out about google 😄
Or until they realize they move faster diagonally than they do if they only move along a single axis
And input is in Fixed Update, not too big of a deal for continuous input but still not the best
i been studying some stuff, and correct me if im wrong but
stateMachine is basically that there is a main value currentState wich determines wich "block/cluster" of functions must play in the update for make it work more organizer and dont overlap?
but now this makes me the question, what diference is between using the stateMachine and using a Int value for each state
There are different definitions of state machine. The strictest one have specific rules to it. If you abstract from these strict definitions, everything in code is basically a state machine. If/else block checking a class field bool or int could be called a state machine.
i meant the enum method
Idle,
Patrol,
Attack
}
State currentState;
void Update() {
switch (currentState) {
case State.Idle:
IdleLogic();
break;
case State.Patrol:
PatrolLogic();
break;
case State.Attack:
AttackLogic();
break;
}
}```
Just having an enum doesn't make it a state machine strictly speaking.
then how i can make it a statemachine?
idk im just seeing that my enemy and player script are too unpolished and i wanted to fix it
Again, it depends on what definition you want to follow. Wiki states this:
"A finite-state machine (FSM) or finite-state automaton (FSA, plural: automata), finite automaton, or simply a state machine, is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number of states at any given time."
FSM i guess
In this case as long as you have some code structure that can have multiple states but be only in one of them at the same time is a state machine.
In more stricter scenarios, it might require you to have separate objects representing the state and the state machine itself
what diferences the previous with this one
void Update() {
if (state = 1){
IdleLogic();
}
if (state = 2){
PatrolLogic();
}
if (state = 3){
AttackLogic();
}
}
}```
The type you use to represent the states.
ah yes i discovered that, the
IState currentState i think it might be called, multiple actors
but i think atleast for me for now is unecessary cuz atleast for what i saw, is only for put what we want it to do when enters the state, updates, and when exits
and i only need to make my script more....organized
oh, but i mean, basically is the same?
interesting
It makes the fsm more robust, readable, extendable and debugable. But it depends on your use case. If it's only ever gonna be 3 states with simple logic, a full fledged fsm implementation might be an overkill.
Everything is relative in programming.
Following the simplest definition, yes, because they're doing the same thing, following the same pattern.
o h
Maybe it would be more like the switch case if you used else if. Because currently you might evelyate several states on the same frame if the current state changes during it's evaluation.
oh right i didnt noticed, xd
Which might actually be what you want. It depends.
but i mean, both methods work for me, but wich one is actually better?
It depends on your use case. If you want it to be readable, I'd use enums.
Because you can expect yourself to remember what state corresponds to what index and even more so of new people that see your project for the first time.
It's also close to the concept of "magic numbers" which is a bad practice
I'm building a 2d platformer in Unity 6
I've imported my tileset, sliced it into tiles, created a rule tile, added the possible combinations with the proper rules. Each tile in my tileset has 4 variants (so I have 4 floors for example).
When I'm placing tiles, the output is not randomly selecting from my list (of 4 floors for example).
Why is it not random and I how do I make it random?
this is a code channel. perhaps you want #🖼️┃2d-tools
I was making a angry bird game i wanted to render my 3 angry bird state according to scenrio like while its on rest it should be this image when i its flying it go to other image and when it hit it goes in 3rd image can anyone help
how can i do this
can somone guide me
i got a big sprite with all the images
is there a way to call all 3 images according to scnerio we can make like when its in air change to this sprite and on collision change to this ?
i can show u code how i have worked so far
this error shows up, i've set up a raycast thing and i think it's failing and crashing, all my objects have a variable assigned
NullReferenceException: Object reference not set to an instance of an object
SelectionManager.Update () (at Assets/scripts/SelectionManager.cs:28)
My line 28: interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
check and log if each reference variable on that line is null . . .
There are a few things here that can be null.
Looks like three possible objects . . .
not very good with unity lingo sorry, can you explain what you want me to do in a more specific beginner friendly way?
Debug.Log("Missing/blank entries are null");
Debug.Log($"Text: {interaction_text}", this);
Debug.Log($"Transform: {selectionTransform}", this);
Debug.Log($"Interactable: {selectionTransform.GetComponent<InteractableObject>()}", this);
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();```
That's not Unity lingo. a reference variable is a programming term . . .
i just meant it in a general way, sorry
Variables are either a reference or a value type . . .
Only reference types can be null . . .
You are using reference variables on that line. You need to look at the line and find each variable that is a reference type. Then use a Debug.Log for each reference variable to check if it is null . . .
so copy this into my code?
it came up with this i think i'm a little slow.. 😭
Did you just copy it into a random place in the script?
I'm just confused because you didn't even place it inside of the class . . .
i am new to coding I don't know where things go
The last line was what you had provided us. Simply place the log messages before that line.
ok thanks so i'll put it before line 28
Do you know what the class is? It's kind of important to know the basics of C# before trying to program, but yes, you should place the code before the line with the error . . .
yes I just forget a lot of things easily and i'm learning that coding is not my strong point haha
Interactable: Branch_03 (1) (InteractableObject)
UnityEngine.Debug:Log (object,UnityEngine.Object)
SelectionManager:Update () (at Assets/scripts/SelectionManager.cs:31)
Transform: Branch_03 (1) (UnityEngine.Transform)
UnityEngine.Debug:Log (object,UnityEngine.Object)
SelectionManager:Update () (at Assets/scripts/SelectionManager.cs:30)
the two above is a grey speech bubble
This one is an error: NullReferenceException: Object reference not set to an instance of an object
SelectionManager.Update () (at Assets/scripts/SelectionManager.cs:32)
Is that what is missing?
can somone guide me too pls
Take a screen shot of the console window in the Unity Editor
In the left image, look for the first blank log. Each log would print what item should have been printed followed by that item.
Click that log. The object with said component script in the scene will be highlighted yellow. Check the inspector for that object and ensure the component has a proper reference for the text variable.
yep i believe it does, at least it looks the same as the tutorial i'm following
That isn't the interaction_text.
i clicked on what was highlighted yellow
Show the script for SelectionManager using one of the two format !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
interaction_text was null but you'll have to figure out why.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SelectionManager : MonoBehaviour
{
public GameObject interaction_Info_UI;
Text interaction_text;
private void Start()
{
interaction_text = interaction_Info_UI.GetComponent<Text>();
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
var selectionTransform = hit.transform;
if (selectionTransform.GetComponent<InteractableObject>())
{
Debug.Log("Missing/blank entries are null");
Debug.Log($"Text: {interaction_text}", this);
Debug.Log($"Transform: {selectionTransform}", this);
Debug.Log($"Interactable: {selectionTransform.GetComponent<InteractableObject>()}", this);
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
interaction_Info_UI.SetActive(true);
}
else
{
interaction_Info_UI.SetActive(false);
}
}
}
}
So interaction_text is assigned in Start. It's gotten from the interaction_Info_UI component.
Check the interaction_Info_UI object that you referenced and make sure it's got a Text component.
yes it has a textmeshpro component
Well, TMPro isn't a Text component.
Try Changing your interaction_text variable to type TMP_Text and your GetComponent<Text>() call in Start to GetComponent<TMP_Text>()
You may need to add the TMPro namespace
Right clicking that error should allow you to add the namespace as a potential fix
The option to import the TMPro namespace - quick actions and refactoring
and then which one? it has more options
sorry for having to have all this spoonfed
I can't see what you see.
Click the first option to import the TMPro namespace ie using TMPro
Likely you haven't finished what was suggested here #💻┃code-beginner message
thanks yes I only did one and forgot about the other when I saw the error
private TMP_Text interaction_text;``````cs
interaction_text = interaction_Info_UI.GetComponent<TMP_Text>();```
You'd need to provide the errors so people can give you suggestions.
Post an update of your code
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class SelectionManager : MonoBehaviour
{
public GameObject interaction_Info_UI;
TMP_Text interaction_text;
private void Start()
{
interaction_text = interaction_Info_UI.GetComponent<TMP_Text>();
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
var selectionTransform = hit.transform;
if (selectionTransform.GetComponent<InteractableObject>())
{
Debug.Log("Missing/blank entries are null");
Debug.Log($"Text: {interaction_text}", this);
Debug.Log($"Transform: {selectionTransform}", this);
Debug.Log($"Interactable: {selectionTransform.GetComponent<InteractableObject>()}", this);
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
interaction_Info_UI.SetActive(true);
}
else
{
interaction_Info_UI.SetActive(false);
}
}
}
}
no errors
Having no errors is usually when things get difficult.
😭
The error is suggesting that the referenced variable interaction_Info_UI does not have a TMPro_Text component.
Modify the logs to this: cs Debug.Log("Missing/blank entries are null"); Debug.Log($"UI: {interaction_Info_UI}", interaction_Info_UI); Debug.Log($"Text: {interaction_text}", this);and click on the UI log.
After clicking, an object in the scene should become highlighted.
Check that object and see if it's got what you expect it to have.
Change your text field to this:cs [SerializeField] private TMP_Text interaction_text;and remove the Start method. Save the script.
In the inspector drag and drop the object with the TMPro Text component into the Interaction Text field of your Selection Manager.
what is my text field?
After serializing the field, you'll see the field in the inspector for the Selection Manager component.
yes but where do i write that code
You should be able to drag the object in the scene with the TMPro Text component into that field.
i already had dragged it in
Have you serialized your interaction_text field?
no i was askign where do i put that line
Instead of relying on Start, simply reference the field from the inspector
Where you declare the field in code
this?
That would be where you'd assigned it.
You should have declared it above as a member of the class.
oh here?
You might want to take some (free) courses on c# and watch some Unity !learn tutorials
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
An example of referencing from the inspector: https://youtu.be/ac7PIcQs178?t=473
This is a basic tutorial on how to use Unity's TextMeshPro UI elements: InputField, Text, and how to code a button click to change these.
If you are already familiar with how to create the UI elements and want to jump to the code section go here: https://youtu.be/ac7PIcQs178?t=235
A very similar video but with Legacy UI can be found here: htt...
i am having to do this for a school assignment and it is due tomorrow 🥲
In your case, you'd drag your object with your text component into that text field.
If it prohibits you from doing so, that object would be missing the necessary component or isn't within the same scope (an asset trying to reference some non persistent scene object etc)
I've got to go, good luck. You're missing the necessary basics to accomplish the current task. You may want to find someone to directly assist you or ask your professor for clarity/help.
i dont udnerstand sorry from what i thought you said was that i put that where it says using tmp_text
ok thank you so much though!
Sorry but this is very basic C# logic. I can't imagine your school is giving you a task without giving enough time to at least learn how the syntax works
In your case you have a field with an attribute sitting in a place where namespaces are defined, which makes no sense. Data goes into a class.
After that you are missing namespaces and therefore many methods and types are unknown. Moving the field to a proper spot might already fix those.
no my teacher doesnt even know this stuff he just told us our assignment gave us two lessons of 'teaching' (watching outdated school tutorials) and sent us off
pretty much everyone in the class is going horribly
My suggestion is that you try making a basic console application and/or dive into some of the basics of C# to learn how the syntax works and how some of its features can be used to scaffold an application
I really don't mind helping with that, but I really suggest you do this without any involvement from Unity. You can't learn both at the same time properly without wasting a lot of time
will do! I appreciate the help as you and dalphat have been very patient, thank you
my assignment is due tomorrow however and i'm just trying to get this over and done with so i can start back from scratch next unit and work through the basics properly
What is it you need to make exactly? I can't imagine anybody would get anything meaningful done if they haven't been teached the basics
I mean I don't mind helping you with this specifically because you seem like you want to genuinely learn it but I would definitely spend time learning C# as soon as you can
You should start with what I mentioned initially, and move the field into the class
"make a unity game"
No, you should be using TMP (TextMeshPro). The one you switched to is old and should not be used.
Not to mention it is not the issue you are having. You need to move the field into the class.
@unique quartz
teacher said he wants us to submit tomorrow anyways
okay!
I mean if it's not a game with any requirements then I'd just make pong or something
i have to have a development journal too and tbh i was debating that now atp but i cant really put in my journal that i gave up and made something else isntead
😭
Well I can't really help with that, especially since I am at work
I don't mind fixing any issues you have though
Did you fix the issue by moving the field?
Hi! There's so many channels and stuff, so Idk where to ask for this, but going to give this one a shot.
So, i'm trying to make a lethal company mod, and they have an sdk thing to replace the player models, but when I import it, it fails to compile with these errors
Library\PackageCache\com.bunya.modelreplacementsdk@91ccd7f277\Editor\RotationOffsetEditor.cs(7,7): error CS0246: The type or namespace name 'Codice' could not be found (are you missing a using directive or an assembly reference?)```
I asked them about it, they didn't know how to fix it so I was hoping someone here have seen these happen before and how they fixed it.
Well, this is a unity problem
got it working, dont really know what I did
the raycast is a bit odd though 😭
it works but it doesnt lol
Hard to say without code
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SelectionManager : MonoBehaviour
{
public GameObject interaction_Info_UI;
Text interaction_text;
private void Start()
{
interaction_text = interaction_Info_UI.GetComponent<Text>();
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
var selectionTransform = hit.transform;
if (selectionTransform.GetComponent<InteractableObject>())
{
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
interaction_Info_UI.SetActive(true);
}
else
{
interaction_Info_UI.SetActive(false);
}
}
}
}```
That looks about as good as it can get tbh
This would mean the raycast hit the object properly, so it might be the object that is at faulth here @unique quartz
I'd check the collision of the object, which is likely much bigger than you think
Draw the ray and where it hits
https://unity.huh.how/debugging/draw-functions
yeah I think it's just a not very good collision box i got a random free asset pack off the unity store so
I'd check what the collision is configured to be through the editor then
how do i do that?
Definitely also try what vertx suggested, even if it's just as a bit of an excercise.
okay!
What is the best way to design a boon system like Hades
Just any general implementation methods I should do
hey all, last week i started going through the unity tutorial and the C# codeacademy course, since i have a game idea i wanted to prototype. considering i am new to both programming in general and unity, is there a particular document or course that teaches how the two integrate and what all the commands available do?
Asking what "all the commands" do is a question nobody can answer, nor is it the right approach to learning to make games (or coding).
The Unity Learn tutorials already teach you how to do both for simple things. Most people turn to YouTube for more tutorials, but you can quickly find yourself in tutorial hell.
Start with smaller projects using what you learned off the things you've already went through, instead of aiming to prototype your game idea.
More of an advanced coding question, but the boons - and most of the other data - can be done as scriptable objects. You'd create an abstract scriptable object class for all boons, with abstract methods for its functionality, and then create the derived ones per boon.
You'd also need a way for the boon to influence in-game mechanics, like "do +25% more damage when hitting an enemy suffering from coffee stained clothes", so a game event system that allows an active boon to listen for the event in progress, read its parameters, check its conditions, and modify its outcome will be handy
Ok that’s exactly what I thought, had to make sure and see if anyone else had a different idea. Thanks
please don't crosspost
https://puu.sh/KvBVs/3aa0680169.png
I get this error, but only when I stop the game. Is it a reason to be concerned, or should I just ignore it?
i had that issue for quite a long while and i didn't notice any effects, but it's not too hard to guard against to prevent potential issues
imo it's unnecessary noise in the console as well
Something on line 57 of Hostile Unit is null but you're trying to use it anyway
If it only happens when you stop the game, it's probably a race condition - something is destroyed before this object that this one depends on
It might be a problem, since it would also throw this error when changing scenes, if this object is a DDOL.
It's kind of an edge case though, unlikely to matter
Yeah, that's what I was thinking. I'm using object pooling. Enemy units add themselves to a queue before they get disabled.
Probably wouldn't worry about it unless either this object or the one that's throwing the NRE are DontDestroyOnLoad objects
I'm using a function that finds the correct queue to add them to. I'm guessing either the queue or function gets destroyed before the unit is
yessir, add some logs to know for sure
functions don't get destroyed
I meant the script the function resides in
Or the component
anyways if the context of the issue is something that won't be relevant for disabling via destruction or scene changes, you could set up a bool that's set via OnApplicationQuit, that'll be called before OnDisable
andy simply make sure ur utilizing those functions..
OnDestroy() OnDisable() etc
The error is within OnDisable
basically "Clean up" before closing
ohahhh u can also see if u can see whats happening w/ the stack thingy at the bottom of the console
shows -> the order -> of how scripts are communicating/getting to that point
what, the stacktrace? this is in a unity message though
ohh
mb
wonder if u could utilize https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Application-quitting.html
you can, yes
this
my enemy pooling did something similar,
my workaround was just checking if the pool wasn't null before adding or removing themselves
there was a forum that discussed that but i don't remember any of the keywords
or a list actually
I fixed it with if (parentPool != null). I should honestly do that more often
void OnDisable()
{
if (isQuitting || enemyList == null) return;
if (enemyList.Contains(this))
{
enemyList.Remove(this);
}
}```
class GameManager : MonoBehaviour {
public static GameManager instance;
public bool quitting { get; private set; } = false;
void OnApplicationQuit() {
quitting = true;
}
}
class PlayerController : MonoBehaviour {
void OnDisable() {
if (GameManager.instance.quitting) return;
/* ... */
}
}
```this is how i did it
huh, i should probably make my singletons use props
your code has been randomly selected for review, please do not resist
On another note, and I know it might not be related. I started getting this one at the same time
Is that normal?
🟊🟊🟊🟊☆
completely unrelated to what we're discussing
I figured
weirdly enough, copying that to my browser, the last star shows up but not the others
must not work across all platforms
ah it's because you got them from different blocks for some reason
chatgpt problems
public class GameManager : MonoBehaviour
{
public static GameManager Instance { get; private set; }
public bool IsQuitting { get; private set; } = false;
void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject); // prevent duplicates
return;
}
Instance = this;
DontDestroyOnLoad(gameObject); // optional: if GameManager lives across scenes
}
void OnApplicationQuit()
{
IsQuitting = true;
}
}``` this was their 5-star "remix"
which is the exact same thing.. but with an Awake() function which im sure u'd have anyway 😅 lol
i wonder if theres a reason that u'd use a flag in the singleton as isQuitting and referencing that.. thats any different than just using Application.quitting
instead of BLACK STAR (U+2605) and WHITE STAR (U+2606) both from Miscellaneous Symbols, you got HEAVY FIVE POINTED BLACK STAR (U+1F7CA) from Geometric Shapes Extended (no white version, only a light version)
wdym?
Application.quitting is an event, not a bool
ik it looks like a bool lol
holy crap lol 🤦
happened to me the first time too lmao
void OnEnable() {
Application.quitting += OnAppQuit;
}``` so something like this then
probably in Awake