#archived-code-general
1 messages · Page 194 of 1
profile it and find out
however I think it's probably better to rely on trigger colliders or physics queries or something of that nature rather than looping through all enemies
class variables automtically show in editor under the script or need the serializevalue ?
They will be serialized if they are public or if they have [SerializeField]
Only one of the two is needed
ty
They also need to be:
- fields
- of a type that is serializable
they were showing in editor but the code didn´t have the [SerializeField] attribute
They'd have been public then
Or your inspector is in debug mode, or you're using Odin or similar
but now i need to reload the scene withoutn reseting them so i can play with the values during gameplay
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
this reloads the init values
how do you prevent that
I mean that loads the scene fresh
The existing objects are destroyed entirely
If you want to save data between scenes you'll need to actually save the data somewhere external to the scene
DDOL objects are one option
i tried that but i think it´s done incorrectly
i just added
private void Awake() { if (!_created) { DontDestroyOnLoad(this.gameObject); _created = true; //Init(); } }
sure but now you'll just have two copies of this thing in the scene next time you reload
you should look into the Singleton pattern
headache intensifies
so it seems like this code is spagethi and adding singleton is pain
all the variables are in the player script and they should be on their own singleton class
Hi, very confusing question so I made a picture. But basically I wanna know how to get a vector3 direction from a gameobjects transform.position to its rigidbody's position?? I tried:
´´´launchDirection = rb.position - transform.position;´´´
but it didn't work, it gave me a result of (0,0,0)
if the RIgidbody is attached to that object then rb.position and transform.position will generally be the same, barring interpolation
I see. So I have to rethink. How do I then get the actual world space position of the rb? Any known tricks to get this?
are you thinking about https://docs.unity3d.com/ScriptReference/Rigidbody-centerOfMass.html ?
Interesting! I will try it out
idk your picture doesn't entirely make sense to me
what are you actually trying to do
like I imported a model from blender where the origin of the mesh isn't in the center of the actual mesh, so it rotates around an invisible pivot
this is because the model is part of many different models, a sort of collection
probably better to put the pivot in the center of the mesh and then put it under an invisible parent object in Unity
but then when I click a button I want the model part disband from the collection in the direction away from the collection
What is the difference between "WasPressed" and "WasPerformed" in the new unity input system?
yeah I thought about that but I have so many meshes part of a collection that it would take ages, so I need a general script to do it for me
I need it to be aligned specifically with the help of the pivot (so it looks like it is part of the collection of models in a very specific manner)
because from blender all the parts have the exact same origin (which is the transform.position, the orange part in the picture)
but I'll try center of mass
note that cener of mass is in local space
so it'd be:
Vector3 worldCenterOfMass = transform.TransformPoint(rb.centerOfMass);``` To get it in world space
Oh I see... so performed is when the interactions tied to a control are done
it didn't work, it still returns a direction of 0,0,0
But I made a test scene in unity with the exact same problem, here is it visually:
Hey guys, could someone assist me with my code? I have a deadline coming up this Friday, and I'm running out of time to complete the assignment.
should I still use worldcenterofmass? because when I do Debug.Log(transform.TransformPoint(rb.centerOfMass)) it returns 0,0,0
I found out you can use rb.worldcenterofmass, but it still returns the same position as the pivot point, not the actual rigidbody hmmm
Does it have colliders?
Center of mass is calculated from the colliders. Weird that it would be zero with that object
I also tried collider.transform.position and it says 0 lol
But yeah if you have a box collider with the center in the cube then you can use that
or like
You need transformpoint + collider.center
Or just make the cube a child and use that childs center
I'm creating a Tower Defense game as a assignment to my university.
I tried to mix two codes, one for path generation (Wide Arch Shark - tower defense video) , with the Tower defense video code the wave spawner (Brackeys), but for some reason I don't know, the enemies generated by the wave spawner are not following the path from the other code. How do I connect everything and make it really work? I'm actually lost here.
I think the main problem is in the EnemyWaveManager under enemy = Instantiate...
If someone is willing to help, I would be more than happy to show the code's
a powerful website for storing and sharing text and code snippets. completely free and open source.
This was it!!! THANKS
just to show the error in game lol
Your chances of getting help are higher if you post the code
Hi I'm a beginner, recently I have came across using scriptable objects as game events from this video:
https://youtu.be/7_dyDmF0Ktw?feature=shared
but I wasn't comfortable with adding assets and importing them as GameEvent in my components from editor, it seems error prone, and not type safe.
so I was wondering what is wrong with using singletons as game events in this way:
public abstract class GameEvent<Type>
{
public delegate void Callback(Component sender, Type data);
public static List<Callback> listeners = new List<Callback>();
public static void Raise(Component component, Type data)
{
for (int i = listeners.Count -1; i >= 0; i--) {
listeners[i].Invoke(component, data);
}
}
public static void RegisterListener(Callback listener)
{
if (!listeners.Contains(listener))
{
listeners.Add(listener);
}
}
}
class PlayerGotDamage: GameEvent<int> {}
class PlayerBuildModeTriggerdGameEvent : GameEvent<bool> {}
what do you think, what are the disadvantages ?
Let's build the ultimate event system in Unity. With just 2 Scripts, you'll improve your programming skills and be able to organise and decouple your code much better! Less spaghetti code and more independent systems!
★ Join the Kingdom:
https://discord.gg/M2qfnUGxAz
★ Download the 2 epic scripts here: https://www.gamedev.lu/game-assets
★ Wat...
Just updated the post with the code lol
FYI you can create a mesh of the collider and with mesh.GetVertices(new List <Vector3>()); you can get all corners. That is quite ez.
Cant really look through all that right now, maybe someone else can or you can try reposting your question here another time.
Meanwhile try to narrow your problem down to fewer lines of code. I dont see any troubleshooting done here
If you dont understand what the code in those two tutorials does then combining them will be hard
hey anyone know how to fix that ?
its show when i try to build the game
part of error 1:
> Task :launcher:preBuild UP-TO-DATE
> Task :unityLibrary:GoogleMobileAdsPlugin.androidlib:preBuild UP-TO-DATE
> Task :unityLibrary:preBuild UP-TO-DATE
part off error 2:
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
D:\myWork\Project\Ninja run\Library\Bee\Android\Prj\IL2CPP\Gradle\unityLibrary\src\main\java\com\unity\androidnotifications\UnityNotificationManager.java:165: error: cannot find symbol
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
part of error 3:
CommandInvokationFailure: Gradle build failed.
D:\2022.3.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "D:\2022.3.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-7.2.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"
this is a code channel. build errors for mobile should probably be directed to #📱┃mobile
you seem to only store a reference to the last spawned enemy so you're only updating that object's position in Update
/// <summary>
/// Start moving camera around.
/// </summary>
private void OnDragmodeUnlockedDown(Vector2 screenPosition)
{
_lastCameraDragScreenPosition = screenPosition;
}
/// <summary>
/// Move camera.
/// </summary>
private void OnDragmodeUnlockedDrag(Vector2 screenPosition)
{
Vector2 differenceScreen = _lastCameraDragScreenPosition - screenPosition;
Vector3 differenceViewport = Camera.main.ScreenToViewportPoint(differenceScreen);
_lastCameraDragScreenPosition = screenPosition;
primaryVCam.transform.Translate(differenceViewport * DragSpeed, Space.Self);
}
I have some code that's trying to pan the camera around when you click & drag. It works, but I have to multiply it by a constant (DragSpeed above). I can't seem to figure out why this doesn't just work 1:1? The constant is about... 9? to get the dragging to match the input.. Any ideas..?
oh and it doesn't work for up/down with the same scale..
I tried using world coords instead of screen coords, and it works "better" with respect to scale, but now I get jitter.. I suspect from trying to move it tiny fractions of world coordinates
Hmmm, the delta is a direction (difference in position) with some scalar magnitude and we're trying to convert that to a point relative to the viewport.. which kind of doesn't make sense to me. Maybe try converting both points then acquire the difference for the translation of the virtual cam?
/// <summary>
/// Start moving camera around.
/// </summary>
private void OnDragmodeUnlockedDown(Vector2 screenPosition)
{
_startDragCameraWorldPosition = primaryVCam.transform.position;
_startDragScreenPosition = screenPosition;
v($"Camera drag starts at screen:{_startDragScreenPosition}, world:{_startDragCameraWorldPosition}");
}
/// <summary>
/// Move camera.
/// </summary>
private void OnDragmodeUnlockedDrag(Vector2 screenPosition)
{
Vector2 differenceWorld = (Vector2)Camera.main.ScreenToWorldPoint(screenPosition) - _startDragCameraWorldPosition;
Vector3 newWorldPosition = _startDragCameraWorldPosition - differenceWorld;
primaryVCam.transform.position = newWorldPosition;
v($"Moving camera to world:{newWorldPosition} (difference from startdrag:{differenceWorld})");
}```
that's the current but.. something is wrestling with cinemachine brain trying to move the camera as well
as far as I can understand, i have all the "brain" of cinemachine brains turned off
oh weird, something else is going on.. every update cycle my drag vector2 position is getting reported as two different vectors:
I'm having a dumb day
var previous = Cam....(_lastC..);
var current = Cam....(screenP..);
var delta = previous - current;//assuming you want reverse direction else it's current minus previous
//_lastC.... = screenP..;
...translate(delta);```
Yeah, I'm not keeping track of delta that way since I thought the rounding was the issue - so I was setting it to "start + difference"
but something else is busted.. those log lines have two different .. "differences"
Try converting the positions before taking the difference.
Hello, what is good type-agnostic way to process input for a movement system I'm making?
wdym type agnostic?
Generics are proving to be a pain in the ass, whenever I have the idea to use them in it
new Input System I suppose
I mean that I could maybe implement the same e.g. script that receives input and adds a force, were it a float, Vector2 or Vector3
all three are value types 😛
Generics seem like could solve that but then I have to create as many dummy classes putting a type into the generic as I want implementations
I realize one problem, I can't be converting and then moving since then the "new" world position will be wrong (since I just moved the camera). I have to save the screen position difference and only after, convert that to a world difference vector
Yes, but it would just be marvelous to have them all share an IAlgebraic or something but they don't
I still don't fully understand what the usecase is
Imagine you wanted to create some rigidbody movement system that worked as well in 2D as it does in 3D
Given that Unity splits the physics, that'd mean you'd have to duplicate the amount of classes/files you have to account for both
And 2D physics usually talk about Vector2, float, etc. while 3D we want Vector3, Quaternions, etc.
does Unity automatically create plain class members of MonoBehaviours ?
I have a plain class as a member of a component, and want to keep it null, unless explicitly created and assigned, but looks like Unity constructs it anyway
However, in a declarative way, what you want is not caring about if it's 2D or 3D but to apply the godddamn force and alike
hard to google question because all the results are related to gameobject instantiation
iirc you can pass a vector3 in any component in unity
even 2D
only if it is serialized. so if it is public and serializable you'll need to decorate it with the NonSerialized attribute. otherwise it will have an instance created for displaying in the inspector
I would guess if they are serialized by either public or attribute they will be created for inspector.
it may be marked as serialized by the attribute, I'll check
Ok, I'll take that, thank you
@hollow stone @somber nacelle thank you, [Serializable] was the reason
it can still be serializable, you just need to make sure that the field you don't want to be serialized is not serialized
if you don't have the class marked as serializable then you won't be able to serialize it yourself for things like saving/loading
yep, trying that rn
it needs to be serialized, so yeah, going to try with the [NonSerialized] in the component declaration
it worked, perfect, thanks again guys
so how can I fix this ?
if you want to update all of the enemies' positions every frame, you should either pass the path to the enemies when you spawn them so that they update their own position each frame, or you need to keep a collection of all of the spawned/living enemies so that their positions can be updated. of course you'd also need to track which point along the path each enemy is currently moving towards so the first suggestion is likely going to be the easiest
hummm, let me try that rq
@dusk apex 😄
was just me being dumb and calculating world position from camera position - which obviously doesn't work since I'm moving the camera in that frame.. actual solution was just:
private void OnDragmodeUnlockedDrag(Vector2 screenPosition)
{
Vector3 tickDifferenceWorld = Camera.main.ScreenToWorldPoint(screenPosition) - Camera.main.ScreenToWorldPoint(_lastKnownDragScreenPosition);
primaryVCam.transform.position -= tickDifferenceWorld;
}
where _lastKnownDragScreenPosition gets updated every frame of a legal drag event after the handlers process it
sorry but i still don't understand.
If the interface of the attack is like
int attack cost
public void AttackEffect()
then how can i implement more then one attack into a single enemy (a class)?
just wanted to say THANK YOU so much, took a while but i managed to get this working :)
that's the problem for anyone that want to help
can anyone help me? im trying to build an android APK but im getting this error, Exception: Unity.IL2CPP.Building.BuilderFailedException: C:\Program Files\Unity\Hub\Editor\2020.3.30f1\Editor\Data\PlaybackEngines\AndroidPlayer\NDK\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++
thats probably not the only error you got there
i deleted all my clang files
now it does not work
can somebody please help
alright i fixed it but im getting another error, Unity.IL2CPP.Building.BuilderFailedException: C:\Program Files\Unity\Hub\Editor\2020.3.30f1\Editor\Data\PlaybackEngines\AndroidPlayer\NDK\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++
Build completed with a result of 'Failed' in 54 seconds (54323 ms)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
UnityEditor.BuildPlayerWindow+BuildMethodException: 2 errors
at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002ca] in <68089899e4c84456bfc1de3436accf4a>:0
at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <68089899e4c84456bfc1de3436accf4a>:0
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
I'm in need of some help, i'm trying to get a game model to show up, but it won't for some reason. Is there any solution?
Oh, i thought it was a coding problem. sorry, wrong room. Though which room is the stuff i need help with? Mainly a model not showing up even though it shows the model in the folder or something, I'm not the best at explaining.
use #💻┃unity-talk .
i don't know what "not showing up" means -- is nothing appearing when you drag it into the Scene View? If so, share a screenshot of what's going on in that chat
when u have both multiplayer and singleplayer versions of a scene, is it preferred to use the same script for both offline and online, or separate scripts?
You ideally shouldnt have different versions/scenes at all, you can launch the game still as a host for the singleplayer
ok thanks, i think that is good and also it is simple
Could someone tell me why my neighbours array here works fine
https://pastebin.com/a9fkLcB9
But once I expand it to include the diagonals neighbours (so I increase the size of the array to 8 too), I get an out of bounds error?
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 same class, but with 8 neighbours instead of 4 (I get an out of bounds error) https://pastebin.com/6mRENrGz
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.
maybe the tile was serialized with just 4 neighbours when you first created? try removing [HideInInspector] from "neighbours" and see how many items appears on the editor
I think this its what you need: [NonSerialized] private Tile[] neighbours = new Tile[8];
currently getting the fault: the type or namespace name 'keyValuePair<,>' could not be found. I'm using System.Collections.Generic, which should contain keyValuePair, but the system still doesn't recognize it. Any help on what my issue is would be appreciated.
it should be KeyValuePair<TKey,TValue> (with K, not k), also you need to specify key and value "types", like: KeyValuePair<string, int>
I moved the new Tile[8] to inside the GetTileData function and it worked
ye, it should work too, but everytime GetTileData its called, a new array will be instantiated to "neighbours"
Ok, trying with the property then
you could write like:
the property:
private Tile[] neighbours;
then inside GetTileData:
if (neighbours == null) neighbours = new Tile[8];
you should be fine
That was it, thank you.
No need, the NonSerialized worked perfect too. Thank you!!
DO you have any resource about this serialize subject?
oh, the unity documentation explains a lot about it, but you should be careful because when you use a public property, unity will serialize its value when you create a new instance of a ScriptableObject: https://docs.unity3d.com/es/2021.1/Manual/script-Serialization.html (Tile inherits from a ScriptableObject)
Why was it being serialized as a size 4 array instead of 8 tho? so weird
When you first created, your code was like new Tile[4]; ?
No, it didn't even had the array
weird 🤔
Wait, the first time I implemented the array
it was new Tile[4]
But the first time I made the tile object, it didn't had the array
I guess the first declaration is what counts
Hey y'all! Does using multiple viewports on different cameras work in windowed mode? Can I do that to make multiple windows with differnt views of the same scene running off the same application?
Guys I have one question I have an array that stores a class of type mobs.
but how do I see the information of the mobs within the array that stores them?
How do you mean? Like access them in code or through the inspector?
Did you import the relevant package?
I can easily access them from the inspector but I'm practicing accessing everything from code
ok so someArray[index] gives you the object at that position, the first position being zero
If you want to iterate over all of them, use a for loop or a foreach loop.
I'm not a mod so take this with a grain of salt, but you might have better luck in the beginner section?
gimme a sec, I'll take some screen shots
I was already able to access the specific methods that were stored within the array, thank you
It was deprecated years ago, and I don't think it will appear outside of the My Assets tab if you've never installed it. Use the starter assets pinned to #💻┃unity-talk if you need a character controller base. Or use the example controllers from the kinematic character controller asset if you're capable of dealing with something more complicated.
And don't cross-post
Unfortunately I don't think I can give out unity stuff without permission? They've taken it off the store page
Is this something I should post in advanced?
Maybe try #💻┃unity-talk
Hello, i tried to make a save system with a binary file, but my existing code return this error now even though i barely touched it :/ May i have some help please ?
also
a save system with a binary file
i hope that doesn't mean you are using BinaryFormatter
the warning seems to get stronger every time i read it
What did you recommand to use if not BinaryFormatter, i got told that's more secure so save file not getting modified but well if it's not secure better to change i guess
the security in question has nothing to do with preventing modifications to the save data. without strong encryption it's not going to be too difficult to modify the save data no matter how you encode it.
it's a malware risk because deserializing arbitrary data with BinaryFormatter can lead to malicious code being executed on your machine. this makes sharing save files (which a lot of people tend to do) dangerous
I meant that i chose BinaryFormatter to prevent modification over XML or JSON
and again, that's not really going to do much to prevent modifications of save files
i understand the risk now though
There are websites that let you upload and edit BinaryFormatter files anyway
Why people keep advising this then -.-
because they are uninformed
this is a code channel
What alternative are you using ?
i personally use message pack to serialize and encode to binary. that's probably not going to be easy to use for someone who cannot diagnose an NRE though. so i'd recommend just using json for now
First it's important to understand that you can't prevent save file editing. You can only make it more difficult. Some basic encryption of plain text files like JSON will prevent most people from being able to edit it. But a person with enough time and skill can still reverse engineer it.
Well i knew it was NRE, i just don't know why it does show me this now, after i wrote the save system. I will delete what i wrote anyway since it's not good
yeah the only true way to prevent someone from modifying their save file is to not even give them access to the save files at all. but then you run into the problem of the game needing to be always online and hosting servers for the data
and even then, that isn't necessarily preventing 100% of cheating and the like
When i say prevent, i mean, not just tweaking number in save file with obvious field to what is what
Then anything that isn't plain text will suffice. You could even just encode JSON to Base64.
Ok, thanks for your advise, i'll do research about JSON then
The real solution is to not care if people mess with their own save files, because why would you
It not like i really care about it, i just don't want it to be easily messed
but why
I think it's a valid concern. Players might report bugs that only happened because they messed up their save file.
Yes and also, i also want to try things as Dev
It's a part of thing that i want to achieve, just to achieve it
I'd like to have the knowledge to do that
@somber nacelle It seems that my NRE come from something being delete on my Scene for whatever reason which my objet was link with, as much i got an UI delete right now for free.
Is there a way for implement the same interface into a class more then 1 time or something that have the same effect?
I need to give some attacks at some characters, but every attack have a different effect, that is a method
The interface type needs to be different in some way, otherwise there would be no way to differentiate between them.
If your interface is generic, then you can implement it multiple times, like:
public class MultipleAttacks : IAttack<Fire>, IAttack<Water>
What do you mean with "generic"? So i can do a lot of attacks with different method body just giving names at the interfaces?
It's a generic type argument. In this example I imagined IAttack might have a generic type argument for the type of damage it deals. Fire and Water would be either classes or structs in this example.
But it's probably not what you had in mind.
Yeah
Maybe an interface isn't the right way. But what i should do other then do a class for every attack in the game?
You could use a delegate instead of an interface, if the interface only contains one method anyway. Then you can use the methods directly, instead of the classes that contains them.
The attacks contain the cost and other things too. Maybe i should do a struct with a delegate variable for the method into it
^
Yeah seems not bad
A list of delegates would be possible too and just implement it into the interface
Not exactly sure of your usecase but I do something similar
Hi, Sorry, I missed your earler post, I meant something like this
public interface IEffects
{
public delegate void Effect();
public event Effect effect;
public void AddEffects();
}
public class myClass : IEffects
{
public event IEffects.Effect effect;
public void AddEffects()
{
effect += Effect1;
effect += Effect2;
effect += Effect3;
}
void Effect1() { }
void Effect2() { }
void Effect3() { }
}
by the way anyone feels like hes making mess with his c# methods?
ive been coding in unity for few years now but i always end up creating a mess where various methods are stuffed in the same files
Try !collab - this server doesn't support collaboration.
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
What's the idiomatic way to return a slice/window of an array in normal unity C#? I saw that Span<T> exists but within the burst compiler bounds, I just need a slice, and by slice I mean a Rust style slice, where it's just an index and a length. I tried to use ArraySegment<T> but I can't seem to find it
Span is the idiomatic C# way
e.g.
var array = new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
var slice = new Span<int>(array, 2, 5);
for (int ctr = 0; ctr < slice.Length; ctr++)
slice[ctr] *= 2;```
And it works with managed arrays?
In Unity?
I must've read wrong while reading google
As shown in this example, yes^
Ok, let me try, thank you
not in burst/job system though
Which napespace is it in
since you can't use managed arrays there
?
Ok, odd, thanks
I must've had the wrong doohickey when I added the thingamajig
Thanks, it compiles, let me test it out
You can use Span with NativeArray in the context of Burst I believe
https://docs.unity3d.com/Packages/com.unity.burst@1.6/manual/docs/CSharpLanguageSupport_Types.html#array-types
https://docs.unity3d.com/Packages/com.unity.burst@1.6/manual/docs/CSharpLanguageSupport_Types.html#span-types
If that's what you were originally interested in
I have yet to tuch the burst stuff
Would you be kind enough to ELI5 the differences between IL2CPP, Burst, and DOTS? I just started working again with Unity since I took a hiatus in 2018 so I'm a bit out of the loop
If you don't mind, no worries, I can google it
I know DOTS is Unity's implementation of ECS, I used IL2CPP back in the day when publishing for mobile, but I'm not sure how burst fits into all this
IL2CPP is just a replacement C# CLR runtime (replacing Mono in Unity) that supports more target platforms and is faster (and is AOT instead of JIT compiled). It involves crosspiling C# code to C++ then building the binary from that C++ code
Burst is a special compiler for eligible code with strong limitations (only blittable non-managed types) and strong performance advantages (think loop unrolling, SIMD extensions etc)
DOTS is an overarching term covering ECS, the Job System, and Burst
I remember the Job system was in beta when I stopped using it. How is burst different from IL2CPP?
It's a completely separate compiler IIRC that goes straight from C# to highly optimized machine code.
(with lots of limitations though)
Right, so it bypasses the transpilation to C++
yes afaik
And I assume it's AOT
yes definitely
It makes sense in the context of ECS
Since the idea of ECS, at least when done right, is to have cache friendly data structures and that mostly requires blitable types
The Job System is a multi threaded scheduler?
It's Unity's own async runtime?
Yeah it's a multithreaded scheduler that hooks into Unity's internal native threadpools
Cool
Well, that clarifies everything
How are people writing code these days? Are they mixing and matching MonoBehaviours with DOTS in those areas where DOTS will help or is there a red/blue function kind of thing going on with DOTS where once you have a couple of things in DOTS, it just makes sense to keep everything within the system?
If you're familiar with red/blue functions
or colored functions
Not sure if that makes sense
Like I never enjoyed OOP in Unity, could I finally fulfill my dream of avoding OOP if I do everything in DOTS?
I've never made a DOTS game yet so I'm not sure. #1062393052863414313 would be a good place to ask
Much to the chagrin of designers I work with
In my experience I do most things in GameObject/MonoBehaviour world and do performance critical things in the Job system
but I haven't used ECS itself
DOTS is a category, you would mix and match monobehaviour (OOP) with ECS.
And yes, you can. It's refered to as a hybrid model.
Ok, cool
I'd have to start digging into it, the current prototype I'm working on would actually benefit from DOTS, as I would like to push the amount of entities on mobile to the tens of thousands
Pure ECS is generally easier than Hybrid though
A lot of things don't play well together
I can imagine
In terms of data ownership you mean, right?
Like where is the data actually located in memory
Well, that and just the monobehaviour physics simply does not work with ecs physics
How difficult would it be to port a MonoBehaviour design (is there a cool kids name for this?) vs a DOTS design?
You have to do a lot of workarounds to get entities and gamobjects to even interact at all
Oh ok, thanks for the heads up
Yeah I mean, that makes sense
Port MB TO ecs? (Remember, it's ecs, not dots that is relevant here. You can use jobs with monobehaviours and even burst if done carefully).
It is tough
It is pretty much a complete rewrite
Oh so what's the difference between DOTS and ECS, I thought DOTS was just a kind of ECS but with burst and jobs if you need them
ECS being the generic architecture
DOTS is the Data Oriented Tech Stack, which includes many packages. The main three being Entities (ecs), Burst, and Jobs
Oh I see
Other than just not being OOP, does Entities have other benefits? Like even with only dozens of entities on screen, is it still more performant?
Is there a good book on DOTS?
I'm likely going to need it for this game, honestly, if not the entity count will be quite limited
I just like it conceptually. I find it easier to develop in.... for the most part haha
are there any ways i can integrate dots into a monobehaviour project and use both in same time?
id use monobehaviors for more complex stuff, and dots for simpler stuff
but no idea what could I use dots for to be honest
because the communication between monos and dots is poor/slow
And yeah, it CAN be more performant even at low entity counts
That's cool
I guess where you might run into trouble is if you use any 3rd party packages that are MB
If by dots you mean jobs, yes.
You can do hybrid between ecs and mono, but it is tough. You need to make a lot of custom solutions
So yeah, if you can recommend a book, I'll read it over the weekend
Yeah, they most definitely won't work unless they explicitly built in compatibility
*depending
I don't like video courses, I prefer books, but I'm only finding this so far, I guess maybe I'll just have to work with the documentation
This is a bit old though
I guess I would just start with ECS
Entities only went to 1.0 this year. DOTS itself is still pretty young
The dots forum has pins with resources that will help.
But yeah, most videos are out of date. There were SIGNIFICANT changes between .50 and 1.0
I don't know where burst and jobs are right now in their stages of release though
Oh.... Burst and Jobs were in development in 2018... I thought they would be ready and relatively mature by now...
You will get the most from just using Jobs and Burst. That's the part that makes Entities fast; good use of Burst compiled jobs. While Entities is still young (well, not really, but it keeps getting rebirthed), Jobs and Burst are very mature and stable.
So I should feel confident developing with DOTS in production for mobile?
I don't like using the DOTS term, because it includes Entities. Jobs and Burst? Absolutely.
Aethenosity mentioned that Entities is at 1.0 but burst and jobs are not, and yet the latter are more stable?
Jobs has been integrated as part of the core engine for many years now. Burst is still a separate package, but had its 1.0 release in 2019
Entities is dependent on Jobs and Burst to work, not the other way around.
I'm sorry if it sounded like that. I said entities is now 1.0, and I don't know where Jobs and Burst are. I knew they were PAST 1.0, but not how stable. I should have said this earlier, but they are pretty stable. Entities is of course a bit larger of a scope than the other two
Yeah, saying "pretty young" is pretty vague/misleading.
I more meant in terms of most people not really using them haha
I would say this is a bit misleading. Chunking/data locality also has a LOT to do with the speed. Without jobs or burst, I see pretty big gains over a similar systems using monobehaviours
Hello, how can Input.GetKey(KeyCode.LeftShift) possibly be false in Update if I am holding LeftShift key all the time? (assuming that I'm actually doing it, it works in other programms and I know where left shift is)
private void Update()
{
print($"LeftShift: {Input.GetKey(KeyCode.LeftShift)}");
}
Do you have Collapse turned on in your console?
yes
turn it off
still false
Then I guess you're not pressing the key? IDK
I am.
Faulty keyboard?
https://keyboard-test.space/
Check your keyboard in your browser
or maybe this is a windows sticky keys thing or something?
Or a different keyboard layout
it worked yesterday and I guess I haven't changed the script where it is chacked yet
everything works.
I think you will find that the shift, ctrl and alt keys do not register on their own. They are key modifiers not keys in their own right
so what do you mean ?
exactly that
I agree. Jobs sort of forces you into good data locality, since you can't easily use objects.
True true.
And don't get me wrong, jobs are great haha.
I have reloaded my pc and it works now.
I have one value in 0.0 to 1.0 range, and other value in -1.0 to +1.0 range. and theyre tracking the same thing but using different ranges
how can i keep them in sync ? so that first variable's 0.5 would be second variable's 0.0
Formula:cs var first = ... var second = first * 2f - 1f;
i see thanks
Dalphat's answer is the best and most efficient.
But if you were concerned more about readablity, you can also do the same thing like this
second = Mathf..Lerp( -1f, 1f, first );
And for more complex ranges, you can use a remap function, which is essentially two lerps
var newValue = Mathf.Lerp(newRangeMin, newRangeMax, Mathf.InverseLerp(oldRangeMin, oldRangeMax, oldValue))
is there a non cheaty way to apply a compute shader to your screen?
wat
Is there a CHEATY way to do it?
Maybe describe what that is so it can be avoided
oh sorry
i can always just take renderimage run it through a compute shader and put it on a canvas that overlaps everything, but i hoped there is a better way
So this is all working right, but the ChangeSlot at the end never runs
possible your while loop is never ending, or possibly the object is deactivated or destroyed before it gets to that line
oh shit your right the while loop never ends
https://hatebin.com/ojqpdaalzg why is the enemy heath bar not decreasing?
again, have you confirmed that nothing else is modifying it and that you are actually operating on the correct image component?
i have
okay and how did you confirm that?
in one of my lines of code I have it so that it can only open that image with the name fill
how about this, put this log right before where you assign the fillAmount and show what it prints:
Debug.Log($"Changing fill amount on {healthFill.name} {healthFill.GetInstanceID()}. Previous value is {healthFill.fillAmount}", healthFill.gameObject);
alright
i also recommend a Debug.Break(); right after the log that prints the new fill amount so that it pauses execution and you can check the state of your scene
like this? '''public void TakeDamage(int damage)
{
Debug.Log($"Changing fill amount on {healthFill.name} {healthFill.GetInstanceID()}. Previous value is {healthFill.fillAmount}", healthFill.gameObject);
Debug.Break();
currentHealth -= damage;
currentHealth = Mathf.Clamp(currentHealth, 0, health);
Debug.Log("Current Health: " + currentHealth);
// Update health bar
healthFill.fillAmount = (float)currentHealth / health;
Debug.Log("Fill Amount: " + healthFill.fillAmount);
if (currentHealth <= 0)
{
Die();
}
}'''
the log that prints the new fill amount is the one after you assign the fill amount
ah ok
the log i gave you should also go right above your // Update health bar comment
Is there a way i could rotate a Bounds struct by 90 degrees increment?
i'm asking specifically 90°, since i'm making (or at least trying) to make a proceduraly generated dungeon, and i want rooms to have a random, 90 incremented rotation on the Y axis
i was originally thinking on just instantiating the prefab room with it's rotation and then creating a bounds and growing them to encapsulate the prefab's colliders, but for whatever reason sometimes the instantiated game object's collider.bounds property return a bounds with center set to 0,0,0. which causes these huge bounding boxes
Swap the width and height
i... guess that would work yes?...
but how would i do that
you mean swap the extent's x and z?
Yes
Let’s say I made a static class which is just one .cs file that I want to share. This .cs file is useful for both Unity and outside Unity. What is the best way to distribute for other people? Github?
Github has gists for sharing small disconnected things without a repo
and is an MIT license needed to let everyone know it’s basically free to use?
Or can I just throw it up and say “Go gettem, champ!”
You can put a license in the gist or find another place to declare the license of all your gists if it's a common theme
ty
you can console yourself by thinking your code will be used to train the next generation of completely useless 'AI' bots
I am writing a code for a simple capture the flag and I have a script called flagpick up that is attacted to my flag object, When the player collides with the flag object it the follows the player. But here is the hard part, I want to when the player collides with the return point object and is also holding the flag to delete, but since the script is attacted to the flag i can only make it work when flag collides with the return
is there a way to reference the player colliding with the return, in a code that is attached to my flag
uh well it really depends on how youre handling the flag being picked up but generally it should not be on the flag's script
this is bad code architecture
you can have something attached to the colliding object
and check if the colliding player
has the flag
then use a switch case statement
okay thank you friend
If you really wanted to hack it, you would have an event on the player trigger that a function on the flag would be subscribed to
Hey guys, does anyone know what I did wrong? Lets say I have a GameObject that has a script connected to it that is using OnDrag, OnBeginDrag and OnEndDrag.
This is the script (Test Script)
https://paste.ofcode.org/cUMhXZXezDUVHJzdPbLGzw
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class TestDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("OnBeginDrag");
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("OnDrag");
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("OnEndDrag");
}
}
Now on the GameObject, I added an Event Trigger in which I added the Begin Drag, Drag, and End Drag and I conncted the same GameObject with the script to it.
But for some reason when I looked up the function, the options for OnBeginDrag, OnDrag, and OnEndDrag weren't there.
Do you want to use the component or script ?
I guess the component. I wanted to call OnDrag and its peers on the Event Trigger Funtion, but it just doesn't show up
is it possible to change what bool your checking for in editor so like if (bool) where the bool is customisable in editor?
Why would you use an EventTrigger and a component with the interfaces on the one object? Afaik EventTrigger is basically the lazy prototyping way to do the interfaces, as it will capture every event
Also, your screenshot isn't showing TestDrag. But even if it was, EventTrigger sends BaseEventData, if your events don't match that I don't think they will appear.
ah, I see
stick with doing everything in code, doing things in inspector is ok sometimes but really bad if you want to find something
code is better because you can search easily through your classes etc
Leave the inspector for designer to do bell and whistle stuff. E.g. confetti explosion.
Ohh the dredd , when you have to make extra spaghetti with the nodes extention to make editor tools 😵💫
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
edit msg, format the code properly
alsorigidBody.velocityin FixedUpdate overrides any AddForces you try to apply
I have a VisualStudio/Unity question. I keep getting these errors when I open a script from unity and my script will open but none of the references to my other scripts are there. When I open multiple scripts each script opens in a new window of Visual Studio, instead of a VS tab. I can still edit my scripts. Anyone know whats causing it?
Configure your !ide to show proper auto complete and intellisense.
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
what happened though? it was working fine yesterday...
Uncertain about "yesterday" but it's not configured today
I have a cloud save system using PlayFab, where the money amount is saved when it has changed or the game has been closed.
The problem is, the player can modify memory (RAM) and set any money value and it'll be saved.
Is there a solution?
Unless you're going to compute the transaction over the network/server, there isn't much you can do if it's on the client side.
how do you always get the original +/- with mathf pow ?
negative values multiplied by itselves return positive values
ofc negative*negative is positive...
nvm got it
i know just was wondering how to get around it but i found a way
you want something like: -(mathf.pow(abs(base),exp))?
not sure, i did this and it worked
float torqueNormal = finalInput * dragInfluence * (horizontalPower * 100f);
float torque = Mathf.Pow(torqueNormal, 2f);
if ((torqueNormal < 0f && torque > 0f) || (torqueNormal > 0f && torque < 0f))
torque *= -1f;
If the exponent is just always 2, then you can just multiply the number * abs(number)
Could even apply the same logic to higher exponents, where you just do the calculation on ((abs(theValue) ^(n-1)) * theValue
Hello,
I'm currently doing a prototype for my 2D game and I'm doing the generation of the levels. The generation of the rooms themselves works perfectly, however, When I atempt to spawn the enemies, I have an issue. To spawn them, I simply add their prefabs (the enemies) in each room prefab (example on the picture 1). It should in theory work well, but actually, it doesn't. Some enemies are working the way they should, and others are bugging. They are in they patrol function but they are just static with a run animation, which should be impossible as I modify the animator speed variable depending on the enemy's velocity. (image 2, video) It's been a week now and I still don't have a clue of how to resolve the bug. I guess that the problem comes from the way I generate my enemies because on a "normal map", they all work perfectly.
Does someone have an idea on what could create this bug ?
I'm not clicking the random files without an extension btw, can you at least make them an image?
Well you clearly show that the speed variable is 1.5 for the stationary archer, so the problem is your code and/or your references.
Can't make more out of it without showing the full code, but if you probably added a:
Debug.Log($"The velocity of {gameObject.name} is: {rb.velocity.x}", gameObject);
(Haven't tested this, just out of my head)
Then you can click on the debug log in your console, and see if the things actually match what you think.
But I think some of the enemies are changing the animator parameters of another enemy.
Hello, I'm trying to find a Job System Documentation about "what are data types that supported in Job System process?"
Anyone have the reference/link?
https://docs.unity3d.com/Manual/JobSystem.html
Thread safe types
Probably this?
Hmmmm... Ok, I'll try, Thank You!
Ok thanks I’ll check that 👍
When i load scene and then load back into the original scene i get some problems:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
I think its the problem that i'm setting the initial value of that 'GameObject through' the inspector but i don't really know what to replace it with,don't really want to use Find for all the stuff
The same problem goes for the second scene, basically if i load a scene second time it gives me that error
it sounds like you are using a DontDestroyOnLoad object that is referencing scene objects so that when the scene is unloaded those objects are destroyed. of course you haven't really shown relevant code so that's really just a guess
Sorry, there's just really a lot of code and no, i haven't used any Don'tDestroyOnLoad since i don't need to have any objects go from one scene to another its just that when i try to use LoadScene on the same scene twice my references dissapear and my guess is it has something to do with me assigning them through inspector and not code but i may be wrong
oh did you save your scene before entering play mode? because reloading the scene during play mode will load the scene that is actually saved in your project
if you mean ctrl+s behind saving then yes, im sure both scenes are saved on needed versions
well make sure you did save. then share the relevant code
did you use any static variables to reference the gameobject or other persistent storage or call async codes
i do have a static class for saving data to json but the error points to this row:
if(_swipeScript.currentButton.GetComponent<FoodSpawnButton>().currentObject != null){
_swipeScript is the object that im assigning through the inspector so i think the missing ref points to it
hmm yes, a single line of code definitely provides enough context to solve this
ill have to dig around for a bit to find which code will be helpful as i have a bunch of it
ok so i've commented those 3 lines as it's not vital but now the problem jumps out right on next line which is
GetComponent<Collider>().enabled = false;
so im guessing it is something not behind smaller parts of code but the scene loading logic overall
until you provide more context, we can only really speculate
well i will be firstly reading some more stuff about the scene loading as both the scenes have the same issue
why don't you just show the full context for where the error is actually happening
public class GrowthController : MonoBehaviour
{
public static event EventHandler OnSellWeightPressed;
[SerializeField] private Button _sellWeightButton;
public FoodSpawnSwipe _swipeScript;
void Awake(){
DataSave.LoadData();
}
void OnApplicationQuit(){
DataSave.SaveData();
}
private void Start(){
_sellWeightButton.onClick.AddListener(delegate {OnSellWeightPressed?.Invoke(this, EventArgs.Empty);});
OnSellWeightPressed += Event_OnSellWeightPressed;
}
private void Event_OnSellWeightPressed(object sender, EventArgs e){
if(DataSave.growthData.weight > 1){
if(_swipeScript.currentButton.GetComponent<FoodSpawnButton>().currentObject != null){
Destroy(_swipeScript.currentButton.GetComponent<FoodSpawnButton>().currentObject);
}
GetComponent<Collider>().enabled = false;
}
}
So here if i comment the part of IF i get the MissingRef for GrowthController script which is strange, its as if it tries to run this script from a gameObject from a previous scene
there it is. it's an event that you are probably not unsubscribing before you reload the scene
see how easy it is to diagnose an issue when you actually provide the full context?
ah damn, now i remember the stuff about unsubscrubing
sorry that it took a bit, just didn't know if getting those parts here and there would help
ok it seems to have worked nicely, thanks!
if vehicle is based on keyboard input, how do people usually insert other velocities into the equation, such as velocity caused by speeding up, or velocity slowed by driving uphills
it seems it becomes some sort of relativity/reference loop where vehicle speed is controlled by both the keyboard input but also by vehicle velocity (that was previously increased by keyboard input)
Hey guys, I'm facing an inspector bug:
Any idea why that might be happening?
The script content is not accessible
The fix is to save a script to force unity to revise scripts. Would have to do that a few times sometimes and it ends up working again.
Which version of unity are you using
2021.3.26f
You reckon it would be solved if I upgrade?
yes the first thing you should try is upgrading to the latest 2021 LTS which is currently 2021.3.30f
I'm gonna upgrade to the 2022 LTS
that's a good idea too if you're willing to do so
For some reason Unity never updates the sprite width, even though it is different, but when I get it with the width property it always returns the same as the first sprite
using UnityEngine;
public class BackgroundManager : MonoBehaviour
{
private Vector3 scrollSpeed = new(-0.01f, 0, 0);
[SerializeField] private SpriteRenderer[] renderers;
[SerializeField] private Sprite[] bgs;
private int bgIndex, bgTransitionCount;
private int bgTransitionTreshold = 1;
private void UpdateBackground()
{
foreach (SpriteRenderer renderer in renderers)
renderer.sprite = bgs[bgIndex];
renderers[^1].transform.position = Vector3.zero;
renderers[^1].transform.position += new Vector3(renderers[^2].size.x, 0);
}
private void ChangeBackground()
{
bgIndex = (bgIndex + 1) % bgs.Length;
UpdateBackground();
}
private void Start() => UpdateBackground();
private void Update()
{
transform.position += scrollSpeed;
if (transform.position.x * -1 >= renderers[^2].size.x)
{
transform.position = Vector3.zero;
bgTransitionCount++;
}
else if (bgTransitionCount == bgTransitionTreshold)
{
ChangeBackground();
bgTransitionCount = 0;
}
}
}
(Which causes a gap inbetween sprites)
no that would be horrid lol
you should not update everytime new update is out esp on active project
Not as far as I'm aware
There's definitely asset store assets and probably some random script out there for it
Ohh thought you were referring to Unity
My immediate thought is ping a server that checks the game version
and if game.version != server.latestgameversion then tell user to update
that seems like the kind of thing a launcher would do, like a diff check
renderers[^1].transform.position = Vector3.zero;
renderers[^1].transform.position += new Vector3(renderers[^2].size.x, 0);
This seems weird, the last renderer you set to Vector3.zero, then you add a vector to it. Is this what you want?
You could just set it to the new vector and don't need the zero vector then, but I wouldn't expect you to do that. Not sure about the rest of the code.
Oh yeah I should just set it
That's my bad
I thought I reset it and then add it again
Either way it does the same
But I should just change it to the proper way lel
yeah the first line here seems pointless
why not just
renderers[^1].transform.position = new Vector3(renderers[^2].size.x, 0);```
Transform tempItem = _currItem ?? _currItemFrame.itemPrefab.transform;
_currItem is null here, _currItemFrame.itemPrefab.transform isn't. Why does tempItem end up being null ?
?? should not be used with anything Unity because it does not take in consideration the "destroyed but not null yet" state of Unity objects
Use a regular null check
if (!_currItem) ?
That works yes
when i try too make a custom cursor in build settings i get Failed to set the cursor because the specified texture ('Rat Cursor') was not CPU accessible.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
and idk how too fix that
so this nice isn't null yet?
Destroy(nice.gameObject);
If it was, you'd get an NRE
I mean after destroying it
In C#, objects cannot suddenly become null. No exceptions. Unity wants that to be the case, but can't, so they fake it by overriding the == operator to return true when compared to null and the object is destroyed.
Yes, it won't be null until nothing references it anymore
Then at some indeterminate time, the GC will sweep over it and it'll really become null
so this will become null?
Destroy(nice.gameObject);
nice = null;
Yes because it reassigns null explicitly to the variable
The previous value still lives in memory until the GC goes over it, but it's not referenced by the variable anymore
thank you, I fixed it by assigning it to null
No need for obfuscation when the server ensures every client action is legal, you have that implemented right?
You're not doing multiplayer right, then
Everything should be validated by a server, or directly handled by the server itself
What's the common way to save data (like a highscore) so that people can use the same Google/Apple account on different devices and keep their highscore?
Unity Cloud Save or other similiar services
didn't know about that, is it expensive?
there is a free tier
noice
but does require CC on file
CC?
credit card
I have an intro video to it too if you want to check it out its pretty easy to use
oh yeah i see it, it is the latest vid right?
yea
i have another one in the works to show how to connect accounts
right now its just anonymous sign in, just to give idea how easy it is to start
thats good ill check it out
Yeah I know, I had a brainfart okay kek
I fixed it though
But the main issue is still a problem
Any ideas? (Anyone?)
is there a way for select some methods to put into a delegate variable from the inspector?
Hey! I'm currently working on a top-down 2D game and am trying to get a game object to rotate towards the position of the mouse on screen. This usually would be easy, but I'm using the New Input System so I haven't gotten very far. Nothing online has been very much help. Any ideas?
nothing online?
i find that impossible to believe lol
just replace Input.mousePosition you use Mouse.current.position.ReadValue()
the rest is exactly the same
or if you want not only mouse use Actionmap or w/e
I was going to also add that I was going to use the mouse posiiton in conjunction with an action map for certain actions, but I thought of a better way of doing it so I won't be needing that. I replaced Input.mousePosition with the Mouse.current and that did work. So thanks!
Hello! I'm in need of some help as I have to start looking for multiplayer online solutions for our game and I don't really know which one to choose honestly 😅
I feel like this is important, and I'm a bit scared of not choosing properly... I'm trying to read some info on pros and cons but everything seems "right"?
sure hope this isn't your first project, multiplayer is extremly difficult to get right.
A good one is the unity Netcode
Not my first project, my first project online tho
It's quite small as only 6 players max per match
But yeah still
I like netcode because its easily integrated into the engine for the most part
Mhmhm I see
I have seen fishnet and photon
Like they are my 2 alternatives apart from netcode
With netcode how does the hosting go? I guess is not as integrated as in photon 
everything is integrated on UGS
you can use Lobby and Relay for example
unity does all the hosting for you
yeah having everything integrated makes it easier
Totally right!
Also if it's first party probably event better as you said
Integrated with the engine
yeah it all works with each oither, they have a free tier too so its easy to get started with them as well
Perfect!
Altho, our game is quite physics demanding, I don't know if it offers like deterministic physics like in photon
Maybe this is a feature I don't really need afterall
😅
id check this out first if you're planning on using physics in NGO
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/
Thanks! Reading right now!
I have found this online too:
It's a comparison between NGO, Fish-net and Mirror
For me rn fish-net is the most appealing solution just because it allows for client based prediction
I don't really have the knowledge at the moment for writing my own
Maybe it's not that hard, but the concept sounds a bit scary not gona lie
Tbh that ngo page about physics doesnt really say much about actually using it.
It gets a bit more complicated when you want server authoritative yet responsive input
Maybe for a fighting party game I don't need to be that restrictive with the responsiveness and physics?
Like, if it was a competitive fps I would need to be very careful
But a fighting game with overcooked visuals maybe can allow itself to be way more relaxed in that aspect
there was another one in the docs but I don't have it on my current bookmarks somehow never did
I had tried doing dodge ball with physics, it was a mess lol I had to opt for using pre-calculated vectors instead of physics bounces..
In basically any movement game itll be noticeable, though depends what approach you take. Client authoritative could work but it gets frustrating trying to sync stuff, server authoritative means you have to deal with input lag which even when low can be bad. Like if you have some delay sending input to host, and the host has some delay sending it back it's always noticeable
the server authorative simulates the physics and all the clients get Interpolated animations, it looks bad
Ngl I was trying some client authoritative physics based game and I might just move on. I (painfully) got the basics working but it's just such a hassle because now im limited in a lot of aspects
Mhhh... Then... Where should I look up to? (Many thanks both of you for mentoring me on this, I appreciate it a lot)
experiment and see what you're willing to sacrifice for accuracy vs speed
there is no definite answer usually
If you have a good team I'm sure you can get it good so dont be discouraged. I was working basically alone (first multiplayer game too) so that's mostly why im moving on. I desperately wanted to get rid of input lag, and I didnt want to try client prediction because mine was an active ragdoll and I thought itd be too much. So I took another approach with client authoritative but now I'm limited because of it
In what way client auth is limited?
Also feel you with that, I'm in a small team too
Thanks for the encouragement ^^
its hard to describe briefly cause its niche. My active ragdoll could pick up a box via a joint so this is 100% physics moving the player and box. If another player grabbed the box, they wouldnt see that the other player is moving the box via physics, they would just see its transform updating and stuff would just start freaking out. Someone (one person only) has to own the box so then i made it so only one can grab at a time. thats a pretty major limitation already
Same thing applies, players cant grab each other
if your game is pretty simple where physics isnt used in everything then you're fine. I tried using physics for everything
Damm with ragdolls and stuff I guess it gets everything even more wild
Idk if I can pass links in here, but I have a trailer
yea tbh i have no clue what some games do to have responsive movement and active ragdolls. Though it makes sense that the games i looked at were all made by studios and there were only like 3
Hva eyou seen bare butt boxing?
you can dm it if u want
i havent seen that one, the ones i looked at were human fall flat, gang beasts, and something else i forgot the name of
Gang beast also has quite a lot of ragdolls
Maybe some of them has more info on that and how they implemented it!
I read that Fall Guys for example implemented their own networked ragdoll physics in Unity
is that link you sent related to what you made or just a reference of the kind of game? it seems pretty simple in terms of physics so i think it should be pretty doable with client prediction/server reconcillation
Yep, thats the game we made!
Now it's all on local multiplayer
Thanks for the advise, at least now I know where to start looking at 🥹
maybe client authoritative could work too, but the part where they are popping balloons would get somewhat awkward. You might run into situations where people see their balloon get popped but on their screen they were safe. Or the other way around
either way goodluck, if you choose NGO i recommend joining the discord pinned in #archived-networking because its more active
Will do! Didn't know that! Thanks
Writing all of this, many thanks for the advise and hope you have luck with your multiplayer experiences
🙌
Hello guys! So, I can drag a Sprite Image to a GameObject (like a cube) through Unity's Interface, but how can I do that in C#?
you mean adding a sprite renderer or do you want to make an object child of another
I'm kind of new to Unity, but I'll try to explain it to you.
So when I get a Sprite Image from my Images folder in my project and drag it to a cube, it's sets the cube mesh to that image. I wan't to be able to do it but automatically with a script.
Take a look at the resources folder
It allows to get assets through code
Here (I hope): https://docs.unity3d.com/ScriptReference/Resources.Load.html
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; // Import the UI namespace for the Text component
public class Page : MonoBehaviour
{
public Text PageCollect; // Reference to the Text component
// Start is called before the first frame update
void Start()
{
PageCollect = GetComponent<Text>(); // Get the Text component
}
// Update is called once per frame
void Update()
{
}
public void CollectPage()
{
// Check if PageCollectCount is not null before setting the text
if (PageCollect != null)
{
Debug.Log("PageCollectCount is not null. Updating text.");
PageCollect.text = "1 / 4";
}
else
{
Debug.LogError("PageCollectCount is null.");
}
Debug.Log("Page Collected");
Destroy(gameObject);
}
}
why is this code not working, when i pickup a page it runs the collect page method, but it will not update the text
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
you can create a material at runtime then apply whatever texture you want, lastly apply it to the mesh renderer
purple squiggly 👀
Using UniTask, how do I await a System.Threading.Task from a library? I am calling an async method from another plugin that I've pulled in.
what's wrong with await?
@leaden ice Maybe I'm a bit confused on how UniTask works... I've run into issues in the past with traditional c# async where I'd get Unity synchronization context exceptions and also just poor performance occassionally. I know they work, but it doesn't appear to be the ideal way to do it. Trying to use UniTask to asynchronously authenticate to Azure using the Microsoft.Identity library. I'm not sure how to use UniTask correctly here. Do I only need to change the return type?
Well, does that code not work?
It does, but I can't tell if I'm using UniTask properly
If it works, then you probably do.
If still in doubt, perhaps look at their documentation. Not everyone here uses the library.
public interface IAmGood
{
public bool IsGood { get; }
}
if(gameObject.TryGetComponent<IAmGood>(out var component))
{
if(component is null)
{
Debug.LogError("interface is null");
}
}
```Hey I have a question about interfaces, if I'm using `TryGetComponent<T>()` method is it safe to use C# null operators? Or anything similar such as
```cs
component?.ToString();
Probably yes.
But you don't really need a null check there anyway. It wouldn't enter the if block if the component is null.
Alright. I saw that method on Unity Huh How and it returns interface type as well as normal GetComponent<T>() method so I was kinda confused
thanks!
I see. In this case it wouldn't be safe to use ?, but you don't need it, since TryGetComponent takes care of it for you.
Alright. I dunno if I told you, in the past I used to create desktop applications using Windows Forms and I was pretty often using null operators, hard to forget about them when switching to Unity 
If you were to use GetComponent instead and check the result for null, that wouldn't be save(in case of interfaces).
Alright, I get it. I'll stick with if(gameObject.TryGetComponent<IAmGood>(out var component)) anyway, looks good to me 
It's pretty simple: unity overrides null checks for the purpose of preventing access to destroyed unity objects. But that override doesn't work with the ? operator, so you might be accessing an object that has been destroyed, causing an error down the line.
This is only relevant to situations where you know you destroy objects and might access them though. If you don't have such cases you might as well ignore that rule entirely.
been inactive from programming for a bit so im coming in like im freshly stupid
how do I like
im trying to do a vector 3 to offset another position
but I want it to be local to the transform's rotation
transform.forward ?
Alright, but still, better to learn at the beginning and use good practices instead of discovering that after X years having headaches trying to find out why it's not working 
Even if not necessary in my simple case, will always work in all scenarios in the future
Anyway, thanks 
EditorGUI.DrawRect(selectionRect, new(1, 0, 0, 0.2F));
```Is there an opposite method? To stop drawing a rectangle? Or should I draw a fully transparent rectangle and pretend nothing is there? 
Don't you need to call that every frame? To stop drawing, just don't call it.
Hello! My top down player gets glitched in a wall when I move it towards the wall. The colliders aren't working properly, this is the video. Any fixes for this, thanks!
In the collision compontent, is the collider Discrete or Continuous? Maybe switching to continuous fixes the issye!
if i have carefully selected values for certain variables, and want to multiply by Time.deltaTime , is there any way to preserve current values/proportions/ratios ? Because multiplying by time.deltatime will result in about 100 times slower values and i will have to spend time selecting proper values again
It was discrete, after switiching it still the same problem continues
Just store the result in a new variable var result = caredullysellectedvar * Time.deltatime
Sorry i think I my post was confusing. My issue is, the carefullySelectedVariable, lets say 100, will become something like 1 after multiplying by Time.DeltaTime
I wanted it to remain its original value (eg 100)
Dont multiply it then ?
but i have to make it framerate independent
If you want to use 100 in the inspector but want the resulting behavior to be 10000, just have it multiplied by 100 in code.cs value = speed * Time.deltaTime * 100;
That way, you can work with smaller numbers to get the behavior of something larger.
but i dont know how much the value is gonna lower when i multiply by Time.deltaTime
100 was just an example
Figure out what the magic number is. Delta time isn't a fixed number.
I'm assuming you're wanting to work with a smaller number under the inspector
Im confused at what you are trying to do. Show some real code
Example: a normalized value
Maybe the gravity? Or how you are calculating the movement
Also angular/linear friction can sometimes do that
Try to play with thay values too
no i want to preserve my values that i used when i intended the game to be 60fps capped (and didnt multiply by time deltatime)
I don't understand
The gravity is 0
But thats what multiplying by deltaTime does….
this is the movement script
Multiplying by delta time would simply give you your value after one second
Instead of per frame
If you have speed at 100 and multi with delta time players on 60fps will move the same amount as players on 240 fps
can anyone help me make an obstacle or refer me to a video that would help. unity 3d
How do I make something happen when something colliders with something
for example my capsule colider and a box colider
https://docs.unity3d.com/ScriptReference/Collider.html
Messages section
Basically include any of these methods in your script that is attached to the object with the collider, and that method will be called when the conditions are met
its working now
But it works when I collide with everything, how do I make it so that it only works when I collide with a specific object
You could check what you're colliding with first
its the ground
okay, I made a tag called obstacle. Now what?
void OnCollisionEnter(Collision collision)
thats my code
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("obstacle"))
{
// Do stuff
}
}
It says that "obstacle is not defined"
then you probably don't have a tag named obstacle
remember that the tag is case-sensitive
the tag is Obstacle, not obstacle then
change it to Obstacle in code
It already is
then it should be working
but it doesnt
The error is gone now but it doesnt work
Here is the Collider for the Obstacle
That's a trigger
{if (collision.gameObject.CompareTag("obstacle"))
{
transform.position = SpawnPoint.transform.position;
} ```
There is a resouce pinned to #💻┃code-beginner that goes over all this if you are ever stuck
{
{
transform.position = SpawnPoint.transform.position;
}``` this works now but how do i make it so that only objects with the tag trigger it
Similarly to how you did it before
This time you can ommit the .gameObject part tho
other.CompareTag("Obstacle")
Yes I saw that on a tutorial but why do we write "other"?
because that's the collider variable name
and you want to check the tag of that colliders GameObject
you can call it what you want, it's the other collider that's involved in the collision
And it'll still work? even if i put some random numbers in?
private void OnTriggerEnter(Collider the_thing_I_collided_with)
{
if (the_thing_I_collided_with.CompareTag("Alien")
{
// Kill alien
}
}```
If it's a valid variable name, sure
The name has to be valid, but yeah
Hello everyone,
I am trying to create a non-monobehaviour script with a static class inside it which should function as a factory of GameObjects
and I want to access a property of the class from the Unity inspector, is it possible?
Serialized Reference
Assuming you want to simply reference the script
If you're wanting to inspect the fields, no.
I want to access this factory class from a monobehaviour script but I also want to change a list of GameObjects on the fly using the inspector
I do not want to attach this script to a certain GameObject (hence not monobehaviour)
Consider scriptable objects for creating instances without game objects
Does anyone know why this code wouldn't be finding any of the colliders on my ragdoll?
Collider[] colliders = GetComponentsInChildren<Collider>();
foreach(Collider hit in colliders)
{
Rigidbody rb = hit.GetComponent<Rigidbody>();
rb.AddExplosionForce(explosionForce, this.transform.root.position, radius, upwardsForce);
}
this runs within a simple coroutine that gets called on start
is this code on a component that is attached to the ragdoll?
are those components inactive at the time you call this method?
i don't believe so
well GetComponentsInChildren will only find active components unless you pass true in as a parameter to find inactive ones
yeah i'm aware of that much
i've just tried to add a rigidbody to the root and addexplosiveforce to that but it didn't work either
okay well the possibilities for why it may not find the components is either that they are inactive or that you are not calling this method on the object you think you are
add this between the GetComponentsInChildren call and the foreach loop:
Debug.Log($"{name} {GetInstanceID()} has {colliders.Length} children colliders.");
ummm so it didn't add anything to the console
but i confirmed that it definitely ran the code using the visual studio debugger
either that code isn't actually running, or it is happening on a different thread somehow. or you just didn't save/compile after adding that line
oh or you are ignoring errors in your console
So something is wrong with the way the explosion force is running then
because I'm an idiot and thought it wasn't finding the colliders because my breakpoint was on that line
but it's just not adding any force to them EDIT : force too low --> fixed
Hey, does anyone know how can I call a method from a scriptable object from its editor?
you can use the ContextMenuItem attribute or something like naughty attributes or odin which both have a Button attribute. or you could create a custom inspector that draws a button to call the method
Yeah I already created a custom inspector with a button but now I'm trying to run a method when I click the button
And I don't know how to access the method from the editor
The method is in a different script
and make sure to actually provide context. you haven't shared code so i have no idea how you've set up your button
public static class Auxiliary
{
static Auxiliary()
{
EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItemOnGUI;
}
static void HierarchyWindowItemOnGUI(int instanceID, Rect selectionRect)
{
// ...
EditorGUI.DrawRect(selectionRect, new(1, 0, 0, 0.2F));
// ...
EditorApplication.RepaintHierarchyWindow();
}
}
```Oh, okay. It's a method I've connected to an event so I dunno how often it's being called 
I guess I need to check my if() statements and how often event hierarchyWindowItemOnGUI is being called by Unity
[SerializeField] private EnemyIdleSOBase EnemyIdleBase;
public EnemyIdleSOBase EnemyIdleBaseInstance { get; set; }
private void Awake()
{
EnemyIdleBaseInstance = Instantiate(EnemyIdleBase);
}```
Good or bad idea to do this for SO?
nothing wrong with that since it will allow you to use serialized data assigned in the inspector on the SO without actually modifying the SO at runtime (since that would change the serialized data in the editor).
(I've used SO a lot...but not getter/setter and certainly no instances 😄 )
my only note for that would be to change the name, there's not much point in including Instance in the name for hte property
sounds good, was following a small tutorial by Sasquatch B Studio and figured I doublecheck that hes doing things correctly 🙂
too many videos I've watched that had horrible coding advice lol
just watched him move lines of code "up" in Visual Studio with a shortcut...and then highlite "private" on all 4 variables and rename them to [SerializeField]
how do you do that 😄
I was looking through them and couldn't see how that worked
(found the move code lines though thanks)
ctrl+w highlights word...not sure how to grab the one above/below it to highlight also
it's multi caret selection
thanks! never would have guessed that lol
I'm having some issues with occlusion.
I have a main_scene that is always loaded and handles most of the logic. (basically has the canvas and camera's, with no largely nothing else, so doesn't have any occlusion data)
I load the map scenes additively, and swap them, depending on what level I'm in.
In editor I can see the occlusion working correctly in each individual level, but when loading them in additively during runtime, it's like the occlusion data never loads.
dont cross post
so, what the hell. SpriteRendeder.bounds.size.y gives 1.37 when the sprite is smaller and 0.58 when the sprite is bigger? it's completely random values
i'm scalling it down with transform.localScale
also the pivot point is at the bottom of the sprite
The inner if statement is not working.
Any Mistakes?
other is a collider not a gameObject
it could not possibly be true
put a tag on it, check for tag instead
eg if(other.gameObject.CompareTag("BoostTag")
yeah a Collider will never == a GameObject
they are different objects, categorically
Also I would expect that to be a ForceMode.Impulse force since it's a one-off
Thanks Dude 🤩
But I used if(other.CompareTag("BoostTag)) and its working good
oh thats right , Collider doesnt need .gameObject. since it has access to CompareTag. Got confused with Collision
👍
Thanks for the message, I thinked about that and it invoked me a dumb idea.
collider == gameobject is not possible, but
collider == collider(gameobject) (from asset)
and it doesn't work 😔
They have to be the exact same collider on the same instance. The collider of a prefab != the collider of an instance
hi i have an question
i am using physic.checkbox
is there an way to get the gameobject inside it?
no, only tells you if you've hit something, not what you have hit
ok so is there an alternative to it?
lots
physic.boxcast works?
Use OverlapBox instead
OverlapBox is the same as Checkbox but gives you the information about what was there
tysm
My transform.Translate's are not working correctly,
Code Snippet: WhitePieces.transform.Find("WKing").Translate(new Vector3(STATIC_SquareSpace * 3, 0, 0));
Vector Output: (-0.144, 0, 0)
(Correct as STATIC_SquareSpace is -0.048)
King location:
Before: 0, 0, 0
After: -0.07199856, -7.638242e-06, -50.00004
What makes you think it's not working correctly?
because 0, 0, 0 + -0.144, 0, 0 is not -0.07199856, -7.638242e-06, -50.00004
transform.Translate operates in local space by default
also is this for chess or something? Translate seems like a poor approach. You should have some kind of Grid class that simply has a mapping from grid coordinates to world coordinates
Probably, but im just messing abt so I wasnt trying to get the best approach
it's unclear what coordinate spaces the coordinates you shared above are in
so it's hard to say what's going on
I'm 100% sure transform.Translate is not buggy though
you're most likely misinterpreting something
transform.Translate operates in the object's own coordinate space, not its parent's coordinate space
so if the object is scaled or rotated, it's going to skew things
What other context would you need, and maybe I just assumed transform.translate, translated it from its current position
it does
so 0x + -0.144x would be -0.144x not -0.07199856x
I would need to know:
- where you read these numbers from
- what the object's position, rotation, and scale are (local and world)
depends where you're even getting these numbers from
and no
not necessarily
because localPosiiton for example is in the parent's coordinate space, but Translate operates in the object's own coordinate space
0 is the transform in the unity inspector
-0.144 is the x of the vector 3 passed into translate
-0.07199856 is the position in the unity inspector after translating
right so sounds like your object is probably scaled/rotated compared to its parent
and you are confusing the parent's coordinate space for the object's own coordinate space
Probably
But telling me im confused is not helping :/
I know im confused bc if I wasnt it would be working
I'm explaining the source of your confusion
Translate operates in the object's own space.
localPosition (the position shown in the inspector) is in the parent's coordinate space
and your king is probably scaled / rotated
its not
so those coordinate spaces are not the same
If you want to move the object in its parent's coordinate space just add to the local position
Or more accurately, how I would edit translate the local position and not the global position
alr
Transform king = WhitePieces.transform.Find("WKing");
king.localPosition += new Vector3(STATIC_SquareSpace * 3, 0, 0);```
I highly recommend you look into the https://docs.unity3d.com/Manual/class-Grid.html component to help you with this
rather than manually moving stuff
I know, As I said I wasnt going to the best approach I was just going for a quick one, but apprently it wasnt quick bc im bad at translate
lmao
just deal with grid coordinates and use https://docs.unity3d.com/ScriptReference/GridLayout.WorldToCell.html and https://docs.unity3d.com/ScriptReference/GridLayout.CellToWorld.html to translate back and forth
Im aware
I duno if I am doing something stupid but for some reason my prefab isn't updating correctly?
When I double click it in the project window it's correct but then when I drag it into scene it doesn't match up
In scene if I click the root there are no overrides
When I duplicate the prefab in the project, the duplicate is correct? 
I'm chalking this one down to a bug
Weird... I didn't even change the prefab, it just randomly broke
Trying to create a sprite from the editor and not at runtime
However the sprite shows up as "type mismatch" in the field
What am I missing?
Hey, quick question, should I use only one instance of System.Random (in a Singleton, for example), or is it better to create a new instance per every script where it's needed?
Depends on your necessary application - multiple seeds etc.
Also consider Unity Random
generally I don't need multiple seeds, but I'm also kinda asking, which way is better for writing good code.
Making only one in a singleton seems to have the advantage, that I won't have to deal with many instances, and so less memory should be used
Unity has a static random you can use instead of making your own singleton
Hey so say I have a compute shader and a rendertexture
on the CPU the rendertexture is defined as argbfloat
on the gpu its defined as RWTexture2d<uint4>
I encode a distance into the z component by doing asuint(distance)
how do I read the float value back on the CPU?(I really only need the center pixel to autoset focus distance)
You could use AsyncGPUReadback for this
Hey there quick question, how do i add stuff to the tilemap, please?
dumb question...why do I need the "field:" here?
[field: SerializeField] public float CurrentHealth { get; set; }
because you are serializing the automatic backing field of the property
Could someone explain the difference between these 2...I've tried to look it up in the past but still dont get why I would pick one over the other
[field: SerializeField] public float CurrentHealth { get; set; }
vs
public float CurrentHealth```
I get if you have a get; private set; but not a get; set;
no difference at all
sweet thanks 😄
Properties are the de-facto standard way of exposing data outside of a class. Fields should not be public (as per the C# conventions)
Also, properties allow you to replace the get; set; with your own code logic, to return custom data, validate the value you're setting, etc.
No not quite a "no difference at all"
as he asked the question there is no difference at all
private int _age;
public int Age {
get => _age;
set {
if (value < 18)
throw new InvalidOperationException("Too young!");
_age = value;
}
}
Validation with custom setter example
gotcha...but in the case that I don't use a custom setter?
still use the get;set one?
Still use a property for exposing public values
What kinda “stuff” we talking about lol
why?
so instead of
[SerializeField] protected Transform center;
public virtual Transform GetCenter() => center;
I just need a getter/ private setter right 😄
Yep correct. A property is merely syntax sugar for a pair of methods
redoing all my old enemy code rn...fixing all my old stuff is "fun" 😭
Conventions. And if you ever need to add validation to the value when you set it, update the setter and it's done. With a field, you'd need to add the validation to all the call sites of said field
are we talking about game dev here or are you trying to teach app dev?
not at all, two totally different paradigms
It's just how you code properly in C#
public Stats stats;
public virtual void SetStats(int tmpHP, int tmpAtk)
{
stats.SetStats(tmpHP, tmpAtk);
}
Is there a way to do this for getter/setter?
or just convert the public Stats stats; to a get;set; and leave function?
If Stats isn't meant to be changed after it's set once, then you can do a public Stats Stats { get; }, and you'll still be able to set individual values inside Stats. Like doing Stats.Something = 42;
The absence of setter prevents the Stats to be changed entirely, not one of its properties
gotcha, Im just creating a Stats object that stores stats
wow chatgpt does things that are so smart that I wouldn't have thought of sometimes 😄
if (playerTransform.position.y - transform.position.y > 1)
{
jump = true;
down = false;
}
else if (playerTransform.position.y - transform.position.y < -1)
{
jump = false;
down = true;
//Debug.Log("enemy down");
}
else
{
jump = false;
down = false;
}
to
float verticalDifference = playerTransform.position.y - transform.position.y;
jump = verticalDifference > 1;
down = verticalDifference < -1;
NullReferenceException: Object reference not set to an instance of an object
Feet.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/sprites/Feet.cs:15)
The parent declaring isGrounded
public bool isGrounded { get; set; }
private void OnTriggerEnter2D(Collider2D collision)
{
var tag = collision.gameObject.tag;
if (tag == "Wall" || tag == "Floor")
{
***parent.isGrounded = true;***
}
else if(tag == "Platform")
{
parent.isGrounded = true;
parent.platform = collision;
}
}
line15 has the stars...why would it say no reference?
parent is null
dont see anything there called parent
whoops sorry 😄
public class Feet : MonoBehaviour
{
Fighter2 parent;
private void Start()
{
parent = GetComponentInParent<Fighter2>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
var tag = collision.gameObject.tag;
if (tag == "Wall" || tag == "Floor")
{
parent.isGrounded = true;
}```
ok, but it can still be null, just because you do a Find does not mean it finds it
gotcha...Im a little confused why it wouldn't be able to find it
obviously because you do not have the component Fighter2 in this or a parent object
this screenshot should show the parent has an "Enemy2" class
and then I showed code that says Enemy2 extends Fighter2
yes, and Enemy2 is not Fighter2
but if Enemy2 extends Fighter2 cant I use Fighter2?
Fighter2 is the one with "IsGrounded"
oh nvm Im stupid
everything Im saying is working as intended
another object is hitting the ground the same time that isn't Fighter2
thanks for the help 😄
this error popped up when i imported visual novel maker asset from the asset store,, how do i fix this??
Switch it to the new class UI.Text like it says
line 13, column 9
thought you should probably just use TextMeshPro instead of Text as thats now obsolete/legacy too
is it a good thing to fire an event in property getter or setter ?
that's a typical pattern, nothing wrong with doing that
is this for me ?
yes
thanks
This is pretty much the pattern for OnValueChanged for most .NET stuff
i did that actually, but another error came up asking what the ''UI'' was
its possible you're missing the package?
if it is in an asset then you probably need to give an assembly reference to its asmdef
nope!! imported everythin
prob this @heady hull
where is that located?? im sorry for being so arrogant
look in the project folder t:asmdef
is anyone using scriptable objects that have a list of other (child) SOs with AssetDatabase.AddObjectToAsset and undo feature?
i cant find it.. im so so sorry
use the filter like you told you
in the search bar
t:asmdef
also show package manager with Packages: In Project selected , doesn't hurt to make sure you do have UI package installed
if(gameObject){//do stuff};
if(gameObject != null){//do stuff};
perhaps a stupid question, but do this achieve the same thing in unity?
if(gameObject??false){//do stuff};
a bit confused on which one to use when doing null checks that is reliable
yes, these do exactly the same thing. the implicit conversion to bool just does == null under the hood
okay, thank you 😄
i read this post
Unity overloads the == operator. Thats why if(gameObject == null) will return false even though the object is destroyed ( but not collected by the GC )
The only safe way to do this check is avoid the == operator and use the ?? instead - that one is not overwritten and plain C#
if(gameObjectToTest??false){
// this will only execute if gameObject is not destroyed
}```
but I don't know if it still applies
that information is backwards. == null will return true if the object is destroyed but null conditional and null coalescing operators will not be able to detect that the object has been destroyed
oh, okay good to know! so i'll just start using ```cs
if(object)
and it will be fine?
like i said before, that exactly the same as comparing to null with the comparison operators == and !=
using those overloaded operators is the only safe way to check if a UnityEngine.Object derived object is destroyed or null. null conditional operator ?. and null coalescing operator ?? and ??= do not use the overloaded equality operator to check for null so they can only check for true null, but when unity destroys an object (which is not really a concept that c# has) it uses what is generally referred to as a fake null because c# doesn't really have the concept of destroying objects like that so variables referencing that object are not actually null until you assign null to them manually
thank you boxfriend, it much clearer to me now :)!
I save level files as JSONs in the application’s persistent directory of my computer. I also want story mode levels that come along with the build. How do I target files in project’s file directory?
Like, if I have Level1.json, my path is something like /Users/Loup/blahblah/Unity/MyProject/Assets/Levels/Level1.json
But how would I get the build to target that level file when it goes onto someone else’s machine?
if Vector2s are not serializable to a file, I'm interested to know how they're saved in a SO for example?
Who said they're not?
try to serialize a Vector2 to a file
Serialize how? There are many ways to do it.
The certainly are. Saving a position vector is one of the first things someone would want to save
"My player was HERE when they left"
they are not
What makes you so confident about it?
I guess I've just imagined doing it all those times. You're right
because when you try to serialze a Vector2 to a file it literally produces an error saying that the type isnt marked as serializable.
Must be impossible then
Are we talking about the same Vector2?
So you take that to mean you can't? I take it to mean you have to mark it as serializeable
no, you clearly can. I guess you guys can't read because I asked how it's done when they're not marked as serializable.
I don't appreciate this hostility
You didn't ask that
Because unity's Vector2 is definitely marked as serializable.
He did though
i did
You asked how it's done in SO's which is YAML using Unity's serializer