#archived-code-general
1 messages Β· Page 407 of 1
like this then?
your code should (in general) make sense if you read it in "plain english"... Your code reads like this:
If the enemy hasn't lost life and the enemy's SCENE is valid, destroy the enemy. Then, destroy the enemy's health bar.
That.. doesn't make sense
[HideInInspector] public bool hasLostLife = false;
So .. yes? but if you're about to destroy the enemy, why are you doing enemyData.hasLostLife = true? You're just about to destroy that object
please configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
i got the plugin wich part?
make sure to follow all the steps
it looks configured π€
So.. your code is all over the place right now and I suspect (?) it's because you're just plugging questions into chatgpt for this.. which is a surefire way to end up with code that's broken and you have no idea why, and we can't really help either since the intent isn't clear. AI generated code might compile and "look nice" but it won't make any sense, and your questions won't be able to make sense either since you don't know what the AI is trying to do.
If you want to delete a game object - then just Destroy() it like you're doing, and having the player singleton for Player.instance.LoseLife() is fine but .. you haven't told us what EnemyData is (a plain class object? a monobehaviour? if it's a MB, is it a prefab? a singleton that contains a list of enemies? etc)
you still seem to have extraneous errors on random methods
there's an error line under Debug.Log?
those are warnings from rider about expensive operations
ohh, mb. what do errors in rider look like?
same as VS - but those warnings are a bit close to that look, i think
the enemies are prefabs
ok - what's Select Enemy? Do you mean selected enemy?
and what's that script on? some sort of singleton "enemy manager" or something?
or is that a single enemy
i got an enemy spawner
ok so .. your enemy spawner needs to instantiate a prefab instance - which will progress along the waypoints and then when it gets there, you destroy it
yeah correct
just stick your whole EnemySpawner into hastebin or some other code sharing site so i can see it
errors and actual compiler warnings and suggestions have squiggly lines, things from riders analyzers like hints about allocations and expensive operations have straight underlines
and Enemy too
the whole thing, not just 2 functions from Enemy
oh ok
what's Enemy.enemies? or Enemy.SpawnTemporaryEnemy()
ah ok, i saw the red and figured the straight line was just how it's styled lol
i don't see where you're instantiating a prefab
ok this is backwards - you should put all this code that manages enemIES (plural) in the spawner
a single enemy should only take care of itself
public class Enemy implies "this is one enemy" not "this is all the enemies"
what does SetEnemy() do or mean? your naming should be more clear..
line 155 is where your problem is
you're creating a new enemy with Instantiate() properly... and then doing nothing with it
the game object you create on line 157 is what you want to destroy
gosh this code is upside down... you're creating a list of "enemy data" to hold your active enemies.. a separate list of "enemy health bars" to hold your enemy health bars.. but you're not trying to delete the instances of those things that you create during gameplay, but the original prefab.
So, take a deep breath, back up and read up on what a prefab and an instance are - you're kind of flailing and just trying to fix lines of code without understanding what you're doing here and this is a mess .. sorry for the blunt words.
In unity, you have prefabs and instances of those prefabs. Your prefab is what you'll link in the inspector, but at run time, when you want to create a single enemy - you INSTANTIATE (create a copy of a prefab) an enemy, and track that as it runs around the world and does stuff - and when it's done, you destroy that copy (not the original prefab).
All of this "enemydata" should be a single script that lives on a single instance - like.. an enemy should know it's own health and update it's own health bar. Your "enemy spawner" shouldn't be trying to coordinate and manage all these specific things about an enemy.. your enemy spawner should just ... spawn enemies, which you might not even really need to track because the enemies will delete themselves later
yeah it manages a lot of things but it also deletes the instances too right because i only get 1/2 warnings
So that's fine, but on line 157 you make a new instance but you don't add it to your list of enemies, so ... you won't be able to delete it
anyway.. i have to run but maybe someon else can pick up the thread here.. but in a nutshell you need to understand the difference in prefabs and instances
thank you for the help tho will try to see if i can get a bit further π
And don't use chatgpt (if you have been).. it's not gonna really help you long term (or short) π
@heady iris do you have some time to look at my code (spaghetti)?
okie dokie π just dunno where to start from here
@cursive lance like i said before please don't go pestering specific people for help
if you have a question, just ask https://dontasktoask.com
then help me lol :/
what is your question
i dunno how i should fix the
you're creating a new enemy with Instantiate() properly... and then doing nothing with it
the game object you create on line 157 is what you want to destroy
Instantiate returns a reference to the object created, store that reference in a variable and pass that object to the Destroy method instead of passing the prefab to Destroy
yeah that sounds nice but then i still don t know how i should implement that 
stop and think about what each object represents
Foo prefab;
Foo instance = Instantiate(prefab);
public GameObject selectEnemy; here it takes the enemy from the list wich is a prefab
and here it picks up the prefab as new enemy
GameObject newEnemy = Instantiate(enemyData.selectEnemy, spawnPosition, Quaternion.identity);
but i get the warning only once or twice that is weird
now look at what you pass in the Destroy method
the gameobject
which gameobject
public GameObject selectEnemy;
which you just said is what?
prefab?
yes. so you are explicitly passing a prefab to Destroy which is the whole problem.
if you don't want to destroy a prefab, then...don't do that
but how can i then acess the new enemy and why do i only get 1or 2 warnings?
where is that reference to the instantiated enemy stored?
christ, looking through your code and this is a lot of spaghetti because you're storing prefabs in the same exact variable as the instantiated object. use the debugger to figure out where you're passing an EnemyData that has a prefab assigned to its selectEnemy.
like wtf is the point of this:
if (enemies.Count > 0)
{
SetEnemy(0);
}
if all that method does is this:
public void SetEnemy(int index)
{
if (index < 0 || index >= enemies.Count)
{
Debug.LogError("Invalid enemy index!");
return;
}
}
because you're storing prefabs in the same exact variable as the instantiated object
this is a very bad idea -- the meaning of the variable now depends on whether you've instantiated something or not
deleted it useless code indeed
so that is whz it is inregualr and gives 2 warnings?
so what should be the next step?
like dunno where i should look at the instantiated form of the variable
use the debugger to figure out where you're passing an EnemyData that has a prefab assigned to its selectEnemy
do you know what a debugger is?
yeah
and you've used it to actually inspect the objects you are working with?
just not really sure how to look for it have used the debugger before but not that expierienced with it
I asked this earlier, but didn't get any answers. Its regarding saving/loading data.
Basically I have a class that is created at runtime by referencing a scriptable object which sets its base data values, int, float, strings.
This is then added to a List and throughoout the game the data values are modified from their original state. These classes are also referenced by other gameobjects in the scene.
What is the best way to go about saving this list of classes in their runtime state in a way that can also be loaded to recreate the list? Is it possible to save other objects/classes that have an associated reference to the class in this list?
gonna go sleep now past midnight guess i will try to fix it then :/ annoying bug
In most cases the answer is: serialize to JSON via https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.2/manual/index.html
I understand this, but what I am having trouble wrapping my head around the basic concept of saving something like a large List of classes. When I try to do so I am only saving the List and the base class. I'm not able to figure out how to save each individual instance of the class that was created at runtime.
also, FYI (to avoid confusion), classes that have been instantiated (via new or any other way) are called objects or instances.
OK, I was trying to avoid saying object since reading you can't save gameobjects for instance
so you can have multiple objects that have the same type which is defined by a class
you can save game objects, its just a bit more process involved as you have to break it apart (component wise) and reassemble it.
most people don't do that, cause its complicated and instead just inject a prefab instance with saved data
if you use JSON, it will serialize the individual objects in the list
you can't really serialize a list without serializing its contents, i.e. it would be pointless
What does prefab instance mean in this context?
you would so something like this:
// pseudocode
string jsonData = File.ReadAllText(filePath);
MyData data = Deserialize<MyData>(jsonData);
GameObject instance = Instantiate(myPrefab);
instance.GetComponent<MyGameplayComponent>().RestoreState(data);
yeah -- you instantiate a thing, then "rehydrate" it
This can be a recursive process.
I see, just means instantiating a prefab and then loading in the saved data. I think that's the part I need to figure out. Writing methods for the things in my game I need to save/load data from so they can be recreated with the saved data vs the base data.
Create a thing, restore its state -- thus spawning more things, whose states you also restore
The real fun begins if you need to remember relationships between objects!
exactly
the principle is straight forward, details can get complicated, but you usually have a choice how complicated you want to get.
the above mentioned relationships between objects are trivial to solve when you build your entire system on top of unique IDs (UID) and UID-lookups. It is much more difficult if the relationships are only ID-based in the serialized data.
a popular approach is a GUID identifier serialized as a string
So with my initial example. I have the List of class instances. Each one has it's data modified from it's base.
To simplify say each instance in the List just has one int variable. If I make the base class serializable then save the List to a JSON should each instance be saved with the runtime data?
Then when I load the game I can create a new List and load in all of the saved class instances in the JSON?
you can restore the entire list from the JSON data
everything will be automatically instantiated and put into the list
(if you use Json.Net that is)
i think you are currently imagining the part that this libary will do automatically for you as the "problem"
which it is, but thats why the library exists
I think I am just using it wrong and need to try again. That's how I expected it to work so I'm overcomplicating things because I was serializing the List improperly.
conceptually what you can do, so long as you are using plain C# objects, you can make up an arbitrary structure of objects and just "save it to disk" and then just "restore it from disk".
Yeah -- it requires more finesse when you're dealing with Unity objects
just look at this very simple example: https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
Also part of my problem is I wasn't thinking about saving when I coded my game. I think I need to rework a lot of it before it gets too complicated so I know exactly what needs to be saved for everything. I've never made a game that is long enough to require saving.
you may want to google the "Memento" pattern to help with that.
Yeah, I need to stop and figure this out and rework things as there are too many moving parts already. I should have been thinking about this from the start.
there is always something "you should have thought about from the start", it takes a lot of time to be able to "think of everything all the time".
One other aspect I'm confused about is how to save multiple pieces of data from multiple classes in one JSON. Say I have player stats, an inventory and then the world state data. So I need to save data from 3 classes in one JSON correct?
If everything is named unique will the library sort that out?
you just need a container object to hold them all, you can save everything to one file.
there will be some grand SaveData object that holds references to every other object
one popular approach is to have a game state class, something like
// pseudocode
class GameState {
Actor[] actors;
Key[] unlocks;
float playTime;
}```
and just save/load an instance of this
then have all game objects look into that GameState to figure out their state and maybe what needs spawning.
but you can do much more complicated things.
you'll discover that it's tricky to record everything that's happening in your game
you want to record enough to reasonably reconstruct the original game state
a good strategy is to design a game in a way that only a trivial amount of data needs to be saved. Some games get away with just saving a list of checkpoints as "passed".
Thanks, this will help me get going. I think the main idea of reconstructing the game state is where I was overthinking. I just need to figure out all the data that changes in my game, save it to JSON, then write methods to load the JSON data and reconstruct the object's state when saved.
yeah, if you can limit the preciseness of your saves, it'll be much easier
You don't have to remember every enemy's position, health, and velocity if you only save at checkpoints after defeating a room's worth of enemies
imagine a game in the old days of console gaming, where you had no memory-cards... these games created savegames by giving players a N-digit code, that would bring them back to a previously passed checkpoint
also, since saving/loading on consoles today is also a truly annoying thing, most console games do only save checkpoints. --> primarily because checkpoints dont easily break when you patch your game to fix bugs or add new content.
My game isn't really real time, its more a management sim. So my plan is to only allow saving during the parts of the game where no direct player input happens. The player sets things up and then plays out the day. So say they finish day 10. I can save all the data to reconstruct their progress on day 10. Day 11 is then generated using that day 10 data.
The reconstructing concept I think helped me stop overthinking it.
thats a good compromise
I'm probably going to consolidate some classes and then create one SaveManager like mentioned that will hold all the object references.
The days are short in the game like 10-15 min so I don't really want to think about trying to save all the runtime positions and states of the NPCs. They have simple decision trees that run on timers. i.e. look around, find thing, go to thing, take thing to register, buy thing, leave store.
if your design allows it, 100% do stuff like "end of day" checkpoints
I think letting the player save between days is plenty.
this will simplify so many things you aren't even aware of yet
My plan was to autosave it after every day, then allow manual save override button so the player can make changes to the store, etc and save before doing the next day.
makes sense
Eventually maybe have multiple save slots, but for now I'll keep it simple.
thats mostly a file management & UI problem
you will also probably want 2 types of save files, one for the player's settings/achievements/meta-progress/statistics, and one the for the actual game-session. But that depends a lot on your design.
It's likely my scripting, but when going from a silent video to a video with audio, the audio does not play. clip change is dealt with in scripting by changing the clip in the player and then sending the videoplayer the play() command
Hello, i'm wondering if there any perfomance difference in using switch or if/else statement in function which should be called often or if it insignificant. I've tried to find something similar but all i found is a switch superioty if used long condition list
Depends on how you are writing the if ... else if ... chain, but yes compiler is pretty smart that in some situations it can lower switch code to better if ... else if ... chains that you would intuitively write.
But also keep in mind that this is micro optimization territory, you shouldn't go rewrite your code and make it worse just because it's tiny tiny bit faster.
Its simple code which should be called often and basically i use if to check if an item is a weapon, consumable or something else to understand what function to call next. I didnt wrote much yet and if its possible i would prefer to make it in a better way from the start
Optimize for code readability/maintainability first, then if you positively identified that it's a problem (I can almost guarantee you it won't be) by profiling, then optimize.
You are way more likely to get significant performance gains from changing some O(n) code to O(logn), than optimizing this piece of code by rewriting if ... else if ... chain into switch and hoping compiler does something smart.
Got it, thank u
you cant do key = Input.inputString
It makes no sense to do that too
Assignment only happens once, so it would only be getting the key when the object initialised
how can I print somethign to check that it is working in unity?
Lemme go to the beginner channel
Can anyone tell me about C#?
I wonder if what I know is correct.
Please. If anyone has just one person, please text me.
Please!
What??
did you even read it ?
hey i am
I want to be good at English
There are several ways to do that,
I think it's a good way to communicate with people overseas.
Information in foreign countries may be different from information in our country.
Hi, i have a big problem with my script: https://pastebin.com/spKrmcy0
although the logic (to me) seems correct for some reason the whole ConnectToNextConveyor() doesn't repeat even though it is in the Update().
I also have a problem when i try to change Orientation it doesn't change the raycast orientation, but i guess its connected to the fact that id doesnt repeat!
Can anyone help me please <3
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.
That's why I saved people
where is the c# question..
It's not a question. Find someone to compare with while communicating with each other!
Maybe...
its very unlikely tbh
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if you have a question about c# ask it
if you do not have a question about c# don't ask
this channel is for help on c#, not conversation or communication
yes
ask your question here, rather than asking to message someone
i need help with c#!
how may we help
i have a big problem with my script: https://pastebin.com/spKrmcy0
although the logic (to me) seems correct for some reason the whole ConnectToNextConveyor() doesn't repeat even though it is in the Update().
I also have a problem when i try to change Orientation it doesn't change the raycast orientation, but i guess its connected to the fact that id doesnt repeat!
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.
Not need to spam. You've just posted your question. Have some patience. If you want to improve your question post more details.
i was just wondering if i posted it in the right format
@astral flame Need to attempt debugging it yourself as well. Debug messages are not to just put success messages, check conditions states to understand what's happening. See debugging guide pinned in #π»βcode-beginner
can anyone help me with this it basically tries to destroy a prefab when it should only destroy an instance but don t know hwo to do it π₯²
Destroy(Instance)
where instance is a GameObject and not a prefab but instance
GameObject newEnemy = Instantiate(enemyData.selectEnemy, spawnPosition, Quaternion.identity);
@cursive lance Put object you are trying to destroy into context parameter in https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Debug.Log.html before the line that throws the error. Then click on the log message it will point to the asset you are trying to destroy.
Show exact line that is throwing the error and what you are printing out to console
The code
Click on the object in the inspector that is "Select Enemy"
Do you see which prefab it points to?
This is what you are destroying.
those 2
You didn't use context with Debug before the line like I told you to either
so just put a red dot infront the else?
Just reread this, it will point to the same thing.
ok, you need to understand the process. Go through the beginning. Where you are destroying the object and getting the error. Just before that line put Debug.Log(" message", contextObjectYouAreDestroying );
Then click on the message it outputs, it will point to the prefab you are trying to destroy.
like this?
Did you click on it?
then it goes to here
Don't double click, just click. It will highlight the object you are trying to destroy.
but that is this?
When you see that it point to prefab, shorten object reference to just enemyData and print it out again, it will point to the object that referencing the prefab you are trying to destroy. Make sure it references instance next time and not prefab itself.
yes, this is the message that highlight object in the context property when you click on the message
then i get a syntax error
Yea, it's not Unity object, can't use in context. Figure out what instance it belongs to and then continue from there. Make sure it references instance next time and not prefab itself.
selectEnemy is the script of the selectEnemy.gameObject it will point to the same prefab
Now you know that it point to which prefab and you know you can't destroy it
You know which prefab. You know where did you assign that prefab. Don't destroy prefabs to fix it. It's pointless.
yeah i should destroy an instance but wondering why i get the warning 1/2 in the game and not the whole time
and don t know how i can fix it
Do you know why you are destroying it at all?
i mean it is a tower defense so if they reach the end i want them to be destroyed
Why are you destroying prefab though. It has nothing to do with instances on the scene.
i don t know didn t want to guess it is an accident
Why are you guessing what's going on in your own code?
because it is quite some code
so how can i make sure it doesn t try to delete prefab but just instances?
if this is possible your logic is flawed, it shouldnt be possible to mix up a prefab and created instances...
When do you have instance to destroy, then destroy it
yeah but now i try to delete prefabs in my code and don t know how to fix it also don t understand why the warning only sometimes happens
prefabs are just resuable assets in your code
your best bet is to just reference the object and Destroy(gameObject) when meeting a condition
EnemyData is to store data about an enemy, but references a prefab? no wonder you have this problem
you should seperate the "enemy preset" and the "instantiated enemy"
e.g. EnemyData is used to create an Enemy and only the Enemy type is used at runtime to do ur logic
https://paste.ofcode.org/CihYVU82MjiMrCRrCkgGhw this is what i have right now
So... important question.
Would every possible permutation of states and inputs have to be coded in a script? Or is there some way to do it more efficiently?
You can use State Machine
Well makes sense why this is happening. You are looping over enemies which are configured with PREFABS but then you also have temporary enemies which are instances. You are confusing yourself by sharing the type for config and created enemies...
yeahh but just dunno how to set it right from here almost done with the game and then i found this error :/
Don't mix up your data for how to create an enemy, and the enemy instances in scene.
yeah i get that that went wrong but don t know how to clean it up/start from here to fix it that is the mainpoint understand the problem
we have explained the issue and ways to correct it:
EnemyData -> Instantiate Enemy -> Set up speed, health, reward values on Enemy -> Process Enemy only at runtime.
i should clarify, I am using Enemy to refer to a NEW script you could make cus your current Enemy class is more of a EnemyManager
if you are keeping prefab references on scripts, at least name them so you you won't confuse them with instances, like myObjectPrefab
yeah don t kno0w how i should do that codewise
got also an enemyspawner script wich just decides how and how many enemies spawn
but you delete instances during the game and prefab are just some object to refer to in your script right?
You can access data on Prefabs and Scriptable Objects assets you reference at runtime, yes.
Just don't try to delete them
yeah i get that by now but i just don t know how to reform the script to only delete the instance π€
start by clearly marking prefabs and check you don't reuse them as instances
if you need to hold an instance, create a field for it
Code refactoring is a large part of programming.
but now i simply need to refrom the script right since i knew by yesterday that i tried to delete prefabs in the scripts wich shouldn t happen but don t know how to rewrite it tought i wasd almnost done with the stupid project and then i got a bug wich i know what is is but not how to fix the code
Okay so in Update() you loop over enemies but in a screenshot above you show prefabs assigned in this list. In this loop you call MoveToWaypoint() for these enemies which then causes the problem.
so solution is... remove this loop?
im so stupid lol
then it makes sense why the error only occurs twice
this is why i suggested not sharing a type for data and created enemies cus its easy to mess up like this.
Anyway you should perhaps rename some stuff, change some types and make it not so easy to make this mistake.
yeah my naming convention or whatever it is called in englisch is bad im just not used to having big projects with a lot of files so structering of the code also becomes a bigger part have only done small webshops and a couple python scripts
Understanding how to structure code and data is a skill you develop over time. Stuff like this often drives you to do better in future π
I understood the flaw in sharing EnemyData because i could foresee a "created enemy" and "configured enemy data" being mixed up easily.
you don't need big project to get the downside of unstructured code. Even small sized code can quickly develop into unmanageable mess. Managing your code is important regardless of the size.
hey guys; just wondering how i could serialize a Unity Material, somehow? i know the engine hates it, but the thing i wanna do kinda relys on it.
I wanna allow players to load their own particle systems in my rhythm game's editor; and having materials be able to be loaded onto those Particle Systems would be kinda epic. It appears Newtonsoft.Json doesn't like doing that though - any way i can get around this?
I have an asset that does it, serializes Particle systems as well
interesting, know where i could get that?
Asset store - Save for Unity
well you can set material properties at runtime as long as you know the name and type. Its not gonna work to de serialize some json into a material as it wont be created properly.
If you know the shader and its main params im sure you can build a way to let a user edit the properties well and apply them.
You could also via shader graph make a shader thats easier to edit to simplify the process.
Or you let them make stuff in unity and export it in an asset bundle that you load at runtime.
And incase its useful, you can import gltf/glb files at runtime and many extensions (lights, materials [usually limited to pbr]) are supported! https://docs.unity3d.com/Packages/com.unity.cloud.gltfast@6.10/manual/index.html
Depends what you mean by serializing the material?
What about it do you want to save and restore?
Just which material it is? That can be done by saving a reference to the asset either via the Addressables Package (an AssetReference) or Resources.Load (The asset name)
Some properties on it? Save them to a custom struct or class and restore in on load.
Its not super simple as a lot of the options you can change on the urp/standard lit materials change many things or change features too
https://www.youtube.com/watch?v=faY50bf4oWs
I have the exact same Problem as this user. Is this a generall problem that anyone here knows a fix for? Or is this problem related to the camera code?
Hi! I am having issues with my Camera jerking heavily when a camera-originated raycast hits an object and enables a Canvas UI item. I have limited it down to the disable/enable of the UI item and the movement script attached to my camera.
The bug is recreated when I move my camera onto the gameObject hit by the raycast with my mouse. If I don'...
0:42
https://pastebin.com/rvAmsfKv
I have this script for my stickman ragdoll enemies. But it doesnt work.I mean doesnt get the triggers from "weapon1 hold" gameobject.I want weapons to collide so I wanted to keep them as colliders but oncollisionenter2d doesnt work if gameobject doesnt have a rigidbody and when I put a rigidbody that is not kinematic, everything messes up.When I put a kinematic one, I prevnt collisions between weapons and thats not something I want. So I added a trigger collider to "weapon1 hold" and a normal collider on "weapon 1". Then, changed oncollisionenter2d to trigger enter.But it never triggers.
this photo is from when I equip a weapon.
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.
game looks like this btw
I'm going to take a shower sorry if someone answers and I reply late.
need a sanity check please: I know I CAN put Unity editor code (like UnityEditor.AssetDatabase ), in my normal runtime code when itβs inside a #if UNITY_EDITOR.
But, if I want to do this for my OWN editor-only-code, I CANNOT actually store this editor-only-code in my projectβs βEditorβ folder (so it compiles to the editor assembly)?
Is this correct? If so, is it because, even with the #if UNITY_EDITOR conditional, the runtime assembly simply cannot access the same-projectβs editor assembly?
Assembly-CSharp cannot access Assembly-CSharp-Editor but vice versa is allowed
makes sense. just not sure how to organize that kinda code. some kinda "EdtrOnly" folder ... I guess.
Asmdefs will overcome the reference issue
not in this case, that would create a circular dependency
Up to you to reference in one direction only
how can i make a 1 way 3d collider?
not a code question
my bad. better phrasing, is there a way to make an object ignore collisions with another object? (probably when it hits a trigger)
maybe i just missed it while searching but i cant find anything
no idea what that is, but it sounds perfect. i'll check the docs now, thanks 
hello, i have been following a tutorial on procedural planets which i almost completed, and i have been trying to add a level of detail system (LOD) but im having issues with chunk generation, the verts and triangles are getting distorted when the chunks are generated and dont know why i get this problem, have been working on it for hours and im really starting to get frustrated, here is the code:
can someone take a look
after reading this and the code, first, i dont know what exactly u want, im confused or probably braindead after debugging for hours, in principle you want oncollisionenter2d to trigger enter, by that you mean this: private void OnTriggerEnter2D(Collider2D collider)?
i mean, i cant find oncollisionenter2d method in your code
I cant add rigidbody that is kinematic or dynamic to my weapon prefab because that messes up things.
but without rigidbodies oncollisionenter never gets called.
So I changed to triggerenter.
It' still not clear what you actually want
if you want collisions between weapons yes they need to have dynamic rigidbodies
when I put a rigidbody that is not kinematic, everything messes up
"everything messes up is really vague. The answer here is to dig down into exactly what is "messing up" and fix that.
My problem is OnTriggerEnter2D() never gets called and enemy never gets damage
let me show you
OnTriggerEnter2D requires at least one Rigidbody
what exactly is messed up when you have kinematic rigidbody, as praetor said, that is important to know
they said when its dynamic, NOT kinematic
sorry vro, didnt noticeπ
From there video there are clearly collisions happening
that means OnCollisionEnter2D will work
the question is just - making sure all the components are on the correct objects etc
when its dynamic,I need joints and some scripts to hold it.When its kinematic collision messes up and weapons dont collide thats why I didnt use it.No rigidbody works fine but I cant use oncollisionenter2D.
So thats why I changed collisionenter to triggerenter
you're better off using Physics queries here instead of rigidbody events
imo
why do you think that
does limbs that weapon hit having a rigidbody check that to call triggerenter?
CHeck what? Again you need to explain exactly which components are on which objects in the hierarchy
You have more precise control over everything, also unlike Triggers (unles you use ONCollision) you don't have for example collision hit point etc.
i don't really understand the question as it is
and because I still want collision between weapons,I added a collider to the root of gameobject that is a trigger and one to the blade gameobject that is a collision.
sounds good
My problem is enemy not taking damage or getting the knockback on the script.
why is the rigidbody on the child ?
you mean the offhandpoint?
yep
its not even a parent so colliders dont get compounded
You added a second rigidbody with no colliders on it
it's pointless
the colliders need to be on the same object as the RB or children of it
otherwise they are not part of that RB
they are part of the parent one
thats because I can equip twohanded weapons to the hand I want. and the other arm gets added a joint, that joint gets connected to the offhandpoint.
So it looks like holding with both hands
and that works fine
ok but I'm explaining why this doesn't make sense if you're wanting to have OnTriggerENter2D or whatever
sounds like you're in a XY problem. You're telling us your fixes / attempted solutions rather than root of the problem / what you want to do
and you didn't show where the script is either
bascially the script needs to be on the obejct with the collider
or on the object with the RB
this is when I equip the weapon
he already told what he wants to do, not the root
I told you that the problem is ontriggerenter in the script doesnt get called. What may be the problems.
thats your attempted solution, not the main problem , Are you doing like a weapon pickup or something
I am fighting with an enemy as you can see in the video
enemyhealthmanager script is on the enemy
named Character (1)
ONCollision/OnTrigger needs 1 dynamic rigidbody between those two objects trigger/colliding
look like you have it a child of the weapon not the weapon itself
isnt the main problem that basically you want to deal damage and knockback but you dont get that (which are called ontriggerenter)
yeah
you dont need it to have a rigidbody if enemy has dynamic rb
okay and which object has the Function OnTrigger ?
that one needs a collider with IsTrigger on
that may be the problem
I didnt know it worked like that
well yeah. Without a trigger how do you expect OnTrigger to work
yeah thats right
but also the enemy has to collide with other things too
so should I carry damaging function to a script on weapon?
A root RB needs that script / function
that script is on the root of enem gameobject
in my opinion that is better so the code is modular and you dont have many things on one script/gameobject
but take it with a grain of salt
alr. So whatever is hitting it needs collider with isTrigger to true
you said the opposite before
what he just said now is correct i think
Either collider needs isTrigger on
nooo its not
up to you which, enemy or weapon
thas why i suggested, for a weapon its easier to deal with Phyics queries like Overlap or spherecast so you never have to worry about rigidbodies.
I thought about that
the problem is you need a lil of over write, but if that isnt is a problem, i recommend you to go for it so everything is easier down the road
can someone help we find out why i get this problem?
realtime gen 
I dont know about lods and procedural generation.
i know nothin sorry
aw man, ty anyway
maybe #archived-code-advanced ? anything procedual seems advanced to me lol
yh, i will ask there
also try the forums/ unity discussion. Unity staff/ Devs lurk there
ty
Why isn't the object moving vertically with my camera?
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.
based on the seams in that image (which look like the corner of a cube), I'd GUESS some kinda floating point issue with these lines: Vector3 pointOnUnitCube = position + ((percent.x - .5f) * 2 * axisA + (percent.y - .5f) * 2 * axisB) * radius; Vector3 pointOnUnitSphere = pointOnUnitCube.normalized * Planet.size;
only other guess I have is .. some indexing issue at the edge.. but these are shots in the dark- pretty complex code to read without more comments
thank you for your feedback, will check if i have issues in that variable, will also add more comments
checked the values and they seem alright, i think the issue is somewhere in this code: `List<Vector3> vertices = new List<Vector3>(mesh.vertices);
List<int> triangles = new List<int>(mesh.triangles);
// Get chunk mesh data
int triangleOffset = 0;
foreach (Chunk child in parentChunk.GetVisibleChildren())
{
(Vector3[], int[]) verticesAndTriangles = child.CalculateVerticesAndTrianglesOfChunk(triangleOffset);
vertices.AddRange(verticesAndTriangles.Item1);
triangles.AddRange(verticesAndTriangles.Item2);
triangleOffset += verticesAndTriangles.Item1.Length;
}`
in the 2 list, i first put the data from the vertices and triangles from ConstructMesh method, so that may be causing problems
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Anyone used the animation rigging package? I need to adjust the position and rotatation of the hand bone and am trying to use it but only am able to get the rotation working
Yeah I did see that channel I was just hoping I could get some quick advice in general. I went ahead and posted my question there with more context hopefully someone knows what the cause of this is cause I am about to just revert back to the built in ik system π€£
If a child collider is hit, OnCollisionEnter gets called on the object that has the rigidbody, so in this case the parent. Its not directly called on the child/collider object. Pretty sure its the same way for OnTriggerEnter.
It is possible to see which one of your rigidbody's colliders was hit, I think it was Collision2D.otherCollider
Hello guys, is there anyone who is familiar with Firebase auth Implementation? I am getting this runtime error, everytime I try to login in from android device. Let me know if you have encountered this before. (I looked up the online forums and tried their methods, still don't have a chance to fix it T_T)
DllNotFoundException: Unable to load DLL 'FirebaseCppApp-12_5_0'. Tried the load the following dynamic libraries: Unable to load dynamic library 'FirebaseCppApp-12_5_0' because of 'Failed to open the requested dynamic library (0x06000000) dlerror() = dlopen failed: library "FirebaseCppApp-12_5_0" not found
dm me with your auth functions
Thanks
Hmm, anyone knows how to view Steam Stats? I can set them or get them with the SteamSDK. But does that mean they can only be viewed from within the game itself?
Not directly a Unity question, but I wonder.
I cannot find info on that heh
Not a Unity Question not a code question either. Ask Steam
I don't understand why only sometimes does it say that MC (orange box) collides with ground tile (yellow) and some other times it does say it collided with shroom tile (blue). I always collide from right
I think it has to do with floating point inaccuracy and the collision point being slightly outside the blue tile rather than inside it
I have a player character using a CharacterController without a Rigidbody. A SwimmingReferencePoint (child of the player object) is attached to the character's neck. When the player enters a trigger collider marked as Water (with a Water layer), swimming mechanics activate, including vertical movement for ascending and descending.
However, when ascending to the surface, the player briefly goes above the water level before gravity is applied, causing them to fall back into the water. Iβm trying to limit the playerβs position so that they can only ascend until their neck is at the water's surface without going above it. I've tried clamping positions and implementing checks but couldn't resolve the issue effectively.
Hereβs a snippet for context:
what would be best solution for this problem
You could make it so that the "enter" and "exit" thresholds are different
Perhaps you have to get 0.5 meters underwater to start swimming, but then only stop swimming once you're 0.2 meters underwater, for example
I've got some pretty basic code to apply force to my object with the wheels controlling the angle.
private void Update()
{
Vector3 trainAimDirection = transform.right;
float engineForce = _engine.CurrentForce; //gizmo only turns green when force is applied
float wheelAngle = -_wheels.CurrentAngle;
Quaternion rotation = Quaternion.AngleAxis(wheelAngle, Vector3.up);
Vector3 rotatedVector = rotation * trainAimDirection;
Vector3 force = rotatedVector * engineForce;
_rb.AddForceAtPosition(force, _engine.transform.position); //engine is located at the gizmo
}```The problem is that even when force isnt being applied and it stops moving forwards, the object continues to spin
What is that bit on the rear/left?
Btw your forces are frame rate dependent in Update, do it in FixedUpdate
all intents and purposes its just an object that stores public float CurrentAngle = 0f; that A/D can rotate
So are you adding sideways forces here or what
this is my attempt at doing that
Its a top down view of a train. The front set of wheels of the train are where the force is applied, and the back wheels are what rotates
Are you holding D to turn right at ~6 seconds?
Yeah
I have to do tiny amounts of rotation for the moment otherwise it gets out to control
Maybe you just want to add some angular drag or manually set the angular velocity to stop it when you aren't turning
That sounds weird, elaborate?
Near the end of the video it starts to pick up too much momentum
Will be easy enough to limit that kind of speed
It just seemed a bit strange for it to keep rotating almost like it was on a ball bearing
no force applied would surely stop all torque
That's false if you don't have any angular drag/angular damping
Think about an object rotating in space
There's no air resistance
It will just keep rotating
ah, true
I'm also not quite sure if the rotation calculation is correct
I think what I have is like this. I take the direction of the red vector and flip it around so the green moves in the opposite direction
in my mind it sounds correct
If the center of mass is between those points then it should work fine
(Which it obviously is, unless you modified it)
yeah its got the default values for that
It didnt feel like I had the full equation worked out, I thought that the length of the train would matter considering the rotation is found at the opposite end to where the force is applied
increasing angular drag has seemed to have worked
I programmed a mouse orbit script. It works great when I use my razer mouse, but if I use a logitech mouse I have it behaves like I am only getting 10 frames a second???
first mouse is the logitech second is the razer i switch around 12 seconds into the video
camera script works fine with a controller as well so im not sure why its behaving like that for one mouse
oh, I've seen this exact problem before, ha
You have a very high sensitivity
The smallest possible movement that your Logitech mouse can report is causing a dramatic change in camera angle
High DPI, right?
Your Razer mouse is more sensitive than your Logitech mouse, so it's moving the camera even faster
which makes the problem a lot less obvious
So really the logitech just made some problem in my code more apparent?
by "sensitivity" I'm referring to how the game turns a mouse delta into a camera rotation
In theory, mouse DPI shouldn't affect how juddery it looks
well, hm..
so to confirm this is the problem crank the sensitivity settings up on my logitech mouse?
You should try turning your in-game senstivity down
then see how it feels with both mice
I just remember reading about issues related to very high DPI mouses, or was it refresh rate π€
I think the latter actually
3 billion Hz
so lowering x and y speed down from 60 to 10 has made it so razerr mouse behaves normal still just slowly but logitech mouse wont move the camera at all
show me the script that handles mouse input
its too long to send here is there a site we use in this server for longer scripts?
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
its still pretty messy tbh
i haven't cleaned it up yet
what is PlayerInputManager?
using UnityEngine.InputSystem;
using UnityEngine;
public class PlayerInputManager : InputManager
{
private InputAction moveAction;
private InputAction lookAction;
private InputAction sprintAction;
private InputAction walkAction;
public Vector2 MoveInput { get; private set; }
public Vector2 LookInput { get; private set; }
public bool SprintInput { get; private set; }
public bool WalkInput { get; private set; }
void Awake()
{
moveAction = input.FindActionMap("Player").FindAction("Move");
if (moveAction == null)
Debug.LogError("Unable to find the move action on player action map!");
lookAction = input.FindActionMap("Player").FindAction("Look");
if (lookAction == null)
Debug.LogError("Unable to find the look action on the player action map!");
sprintAction = input.FindActionMap("Player").FindAction("Sprint");
if (sprintAction == null)
Debug.LogError("Unable to find the sprint action map!");
walkAction = input.FindActionMap("Player").FindAction("Walk");
if (walkAction == null)
Debug.LogError("Unable to find the walk action on the player action map!");
}
internal override void CollectInput()
{
MoveInput = moveAction.ReadValue<Vector2>();
LookInput = lookAction.ReadValue<Vector2>();
SprintInput = sprintAction.IsPressed();
WalkInput = walkAction.WasPressedThisFrame();
}
}
using UnityEngine.InputSystem;
using UnityEngine;
public class PlayerInputManager : InputManager
{
private InputAction moveAction;
private InputAction lookAction;
private InputAction sprintAction;
private InputAction walkAction;
public Vector2 MoveInput { get; private set; }
public Vector2 LookInput { get; private set; }
public bool SprintInput { get; private set; }
public bool WalkInput { get; private set; }
void Awake()
{
moveAction = input.FindActionMap("Player").FindAction("Move");
if (moveAction == null)
Debug.LogError("Unable to find the move action on player action map!");
lookAction = input.FindActionMap("Player").FindAction("Look");
if (lookAction == null)
Debug.LogError("Unable to find the look action on the player action map!");
sprintAction = input.FindActionMap("Player").FindAction("Sprint");
if (sprintAction == null)
Debug.LogError("Unable to find the sprint action map!");
walkAction = input.FindActionMap("Player").FindAction("Walk");
if (walkAction == null)
Debug.LogError("Unable to find the walk action on the player action map!");
}
internal override void CollectInput()
{
MoveInput = moveAction.ReadValue<Vector2>();
LookInput = lookAction.ReadValue<Vector2>();
SprintInput = sprintAction.IsPressed();
WalkInput = walkAction.WasPressedThisFrame();
}
}
okay, so that's just pulling from input actions
and you aren't multiplying by deltaTime erroneously
I would look at the actual values you're getting from the two mice.
Make sure to print them out with more than two digits of precision (that's all you get by default)
I believe you can do something like...
Debug.Log(MoveInput.ToString("N8"))
i think that's how you contorl the formatting?
kind of obvius actually when he said one mouse act like that and the other like that
I think I found an issue
this is from th e "working" mouse
its always whole numbers
did you set the input action to be Digital?
I'll stop for today but check this logic out later. Somewhere there is a stupid error im sure but too bored rn π
it should be a "Vector 2" control type
do you have a processor on the Delta [Mouse] binding?
hm, looks fine
I guess this would make sense if the razer mouse is reporting so fast that it catches every single movement
the logitech mouse isn't a gaming mouse its just some crappy office mouse
but it woorks fine in valorant
But multiple mouse inputs during a single frame should be getting summed up
you can also look in the Input Debugger window
window > analysis > input debugger
it should show the same values
I see values that are always multiplies of 0.25 for the delta down/left/right/up
THE CODE WORKS NORMAL WHEN THE INPUT DEBUGGER IS OPENED
what
400+
Does opening it reduce your framerate noticeably?
yeah, see if that changes the behavior
So with the logitech mouse, do you get many frames of 0 input and then a few frames of very large inputs?
Yes
but this mouse works fine in other games
i can play val at 240 fps and the mosue is smooth as butter
I wonder if it's pulling input from the mouse differently than Unity is
Can you check how many frames of zero input you get at a time?
like, is the logitech mouse giving input at 60Hz? 120Hz?
that kidn of thing
You could do this by logging
Debug.Log(Time.frameCount + ": " + LookInput.ToString("N8"));
sec i gotta relaunch the editor
unity keeps the fps locked even after removing application.targetframerate
ok so when i start moving the mouse it reports 1,-2 then zero for two frames then more valid input then zero for 2 frames
yeah, it'll stick -- you can set it to -1 to unlock it
That certainly explains the jumpiness. It's odd that you wouldn't see that in other games, though
ima see what happens if I use the old way to gather input
same behavior sadly
i may have found a fix tho
nvm
I'm trying to create a function that will let me check the area in front of the player for objects, but I want to be reusable for different interfaces. I currently have this:
public bool TryGetObjectInFront<T>(out T interfaceObject) where T : IPlaceable, IHoldable
{
// Do stuff
}
I am calling it like this:
if(player.TryGetObjectInFront<IPlaceable>(out IPlaceable interfaceObject))
{
// Do other stuff
}
However, this is giving me the following compiler error:
"The type 'IPlaceable' cannot be used as type parameter 'T' in the generic type or method 'Player.TryGetObjectInFront<T>(out T)'. There is no implicit reference conversion from 'IPlaceable' to 'IHoldable'."
That error doesn't happen if I remove IHoldable from this line:
where T : IHoldable
Is there some syntax issue here? How can I make the generic function accept both of those interfaces?
where T : IFoo, IBar demands that the type implements both interfaces
Ah, that's the issue then. Is there a syntax that would accept either? I'm not finding that online.
You would need to do:
if(player.TryGetObjectInFront<SomeClassOrInterfaceThatHasBothInterfaces>(out IPlaceable interfaceObject))
{
// Do other stuff
}```
e.g. if you had
public class Interactable : IPlaceable, IHoldable``` then you could do ```cs
player.TryGetObjectInFront<Interactable>```
You could define two different methods that each call for a single interface type.
Or if you had:
public interface IPlacableAndHoldable : IPlaceable, IHoldable``` you could do `player.TryGetObjectInFront<IPlaceableAndHoldable>`
C# does not permit for this kind of "either" type
(I know Typescript can get really wild with that stuff)
or you could make a third interface
Yes as in this example
It sounds to me like you shouldn't require either interface, though
You're just getting a ... thing that's in front of you
it doesn't have to always be placeable or have to always be holdable
I want to create a function that will look for objects in front of the player, but filter for specific interface. I will need to recreate this exact function for each interface. So it sounds like there's not a way to have a function take the interface type (for example IHoldable)?
!code (ignore this)
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
The purpose of this function is to look for objects the definitely have such an interface.
It sounds like you just want this
public bool TryGetObjectInFront<T>(out T interfaceObject)
{
// Do stuff
}
much like how GetComponent works
You need to just get rid of the generic type constraint and check for the interface T at runtime
(You may want to add a constraint that it's at least a Component)
wait, no you can't do that
these are interfaces
If you want to constrain the kinds of things you can look for, then I suppose you could make some kind of empty IQueryable interface..?
public bool TryGetObjectInFront<T>(out T interfaceObject)
{
if (Physics.Raycast(..., out RaycastHit hit) && hit.collider.TryGetComponent(out T comp)) {
interfaceObject = comp;
return true;
}
}```
something like this
you probably don't need that intermediate variable either
The way I handled this in the past, I created Rect for each object I wanted to be interactable with, then I added a rect around the player and used a spatial hash to get all nearby items, loop through if the rects intersect
AH, yeah that was it... I should have tried that first. I'm not sure why I thought this needed a constraint. For now, it seems to be working with just this:
public bool TryGetObjectInFront<T>(out T interfaceObject)
Can also like include the interface onto other interfaces and ignore generics completely
then check by that interface type
The interfaces should be separate. There could be any combination of holdable AND placeable, just holdable, just placeable.
And I think there may be other interfaces in the future that could be added to this list, so it would quickly get out of hand if I tried to create like IHoldableAndPlaceAndThrowable or something like that.
Or just IDetectable even
Ah, that's not bad. I'll keep that in mind in case I need to revisit this.
hi there
I'm trying to make a script for moving platforms. now i need platforms to go to second point and teleport back to first point
The problem is that platforms move to second point and stop there instead of going to first point (teleporting to it)
https://paste.mod.gg/rwtihgwynwmn/0
A tool for sharing your source code with the world!
(previous link was wrong, it was code by ai (which didn't help))
so you've set lap and instantReturning to true, correct?
and also loop?
Is there a way to click and drag a non monobehavior script into the inspector?
only if its an asset (inside a MB eg SO) so no
like I have a list of List<SomeCustomClass> on a scriptable object. I want to be able to drag non monobehavior scripts into that list in the inspector
is there no possible way to do this?
they'd have to be SOs as well
where are you expecting to drag from?
the c# file
that ain't gonna work
You can the file itself but it not work how you want it
its essentially just a TextAsset
what about types
can I make it so I can set up a list of types in the inspector then create instances of those types via reflection?
that's not gonna fly either, Type is not serializable by Unity.
Best you can do is a List of strings. each string containing a fully qualified type name
you can then create a Type from that and then use that Type to create an instance of the Class
no sir i am trying to create a way to attach leightweight behaviors onto things like weapons, items, AI etc. I do not want to use scriptable objects for the behavior cause thats not what they are for. I do not want to use monobehaviors for them cause they're bloated. so I was going to make a leightweight behavior class that other classes can inherit from, and I want the "behaviors" to be assignable to the items scriptable object that holds data like its display name and model etc.
how exactly are they bloated?
this sounds like you're just doing skating around the same problem but in a more overconvoluted solution
which problem?
scripts as behaviors, has been exhausted to death and essentially you end up either using SOs or regular POCOs
Ooh, I see what you want
You're going to want to check out [SerializeReference]
It allows you to serialize a List<ParentType> and actually store specific child types
There is no built-in UI for this, but there are several packages
do they have to be monobehaviors tho?
No. They're explicitly not unity objects
awesome
If you're storing references to unity objects, the problem is already solved (an Object field can hold any Unity object, no matter what the exact type is)
I use this all over the place.
You can do this without [SerializeReference], but Unity will only remember serialized properties for the parent type
So it doesn't really work
for example, I have a List<PerspectiveHandler> here. PerspectiveHandler is an abstract class
I can pick a specific derived type and then configure it in the inspector
If I didn't use [SerializeReference], it would only remember the serialized properties of PerspectiveHandler (of which there are none!). It wouldn't be able to remember that I had put specific concrete types into that list
So just so I am clear in your scenario the attribute goes on the class itself right?
No, [SerializeReference] goes on the field.
Have a look at the repository I linked
You will need to use a third party package to get an actual inspector interface.
Unity does not provide one.
(I'm actually using another package here -- this is provided by Animancer -- but it's the same idea)
I use this anywhere I need to pick between multiple derived types
So, for example, my Entity class has an Anatomy field that tells you where you should look when focusing on the entity, amongst other things
yeah this is awesome I am glad you showed me this it opens the doors to a lot of code cleanup
I have various Anatomy implementations that handle that differently
I am going to use this weapon behaviors
I used to do this by creating ScriptableObject assets of specific types and then throwing them into a List<BaseType>
This is fine, nominally, and it has some advantages -- you can easily re-use the assets in many places
But if this is describing something that's totally unique to the user, then it's a hassle to create a massive pile of assets
loop and instantReturning are set to true, yes, but lap no because for two points it shouldn't matter
There are a few "gotchas" to watch out for
this is what i was trying to avoid
Most notably: If you change the namespace, assembly, or type name, Unity gets upset. It's not storing the GUID of a MonoScript -- it's literally just storing the type's full name
There is an attribute you can use to tell Unity about an old namespace/assembly/name for a type
[UnityEngine.Scripting.APIUpdating.MovedFrom]
I went for a more direct solution: I wrote a Python script that rewrite your assets
It feels a bit gross
(it's literally just regex)
I was doing a very large namespace migration -- from one enormous root namespace to a bunch of namespaces
so that was helpful
you'll probably want to start debugging values then
see how it flows
note that this is just one major use of SerializeReference (the second one that gets listed)
I've never used it for the first case, where you're serializing things like graph structures
wdym?
Im so excited to have found out about this my code about to make a ton of use for it
btw SerializeReference works also for generics since unity 6
start logging things and see if they're the values you expect
i might understood what you mean
some times i wonder if i use too many attributes... nah my code is perfectly readable /j
(just noticed that first variable isn't meant to have the conditional field attribute, whoops)
Guys, I've been struggling so long and don't know how to make this work
everything is wrong with it
it works well outside of tight tunnels cause it's a lot simpler, but it seems impossible here
can you show us the !code ?
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
would be more readable with one attribute per line
It's a mish mash of several differet scripts that control the raycasts, IK targets, rotations etc
o yeah, i usually do that with the tooltip attribute. the rest usually have the same size so they dont look too jarring when reading the code. i've started adding custom ones recently. its getting out of hand with some scripts 
do you have any idea of what specific one could be causing the issues?
I mean it's a host of issues I guess
raycasts are hard to control in such a tight space
I did a lot of logic for them and they kind of work
but my hands take up too much of the screen and clip through the camera
also sometimes I get weird angles for surface normals, can't really control that
idk anyone have a better idea to control hand grabbing here?
if you want another solution, you could just fake it. you can manually animate the hands and have the animation play while moving
im not entirely sure what else you could do. maybe someone else does though
I have it so it raycasts left when I move left for example
or what if I'm crawling through a wall
they would clip with normal animations
you could have them be rendered by a separate camera
it would look something like this
I already do that
but you can still notice something's not right when it's clipping hard
clipping with the camera or the terrain?
nvm, watched the video you sent again and i see what you mean
i haven't actually done much with this myself so im not 100% sure of how to fix that
but, i think its just because the animation is a little weird
the ik animation
fyi you can combine attributes into the same []. e.g. [SerializeField, Tooltip("foo")]
can also use newlines to save your eyes
Is there a way I could create a system script that doesn't need to derive from MonoBehavior but has Update/FixedUpdate loops & behaves like a singleton? I want to make my system scripts similar to how systems work with Unity's ECS but with regular GameObjects
- Use ECS SystemBase
- Drive such a thing from a MonoBehaviour
- Modify the PlayerLoop
if you use something like UniTask and have an async function, that can utilize the update loop without needing a MonoBehaviour.
*i did not know this
*
can also do:
[field: SerializeField]
public int MyProperty {get; private set;}
o, i did see someone mention that one a few days ago
i've learned a surprising amount just by reading chat, in the short while that i've been here lol
on the topic of ECS, is there a way to use the DOTS workflow without having to 'bake' prefabs?
Sure there's nothing forcing you to use GameObject authoring in DOTS but it's often the most convenient way.
like, have they implemented a way to create/modify entities in the edtior window without prefabs?
I see
YOu can always create Entities and do whatever you'd like in code
no, GameObject based authoring is the supported way of authing things in the editor
So it appears serializableref also works with structs as well.
but what I was mentioning is you can just use a SystemBase from ECS without using entities at all
you can freely do GameObject stuff with that.
I understood that, I was just going off track a bit haha
do you know if there's any plans for solely Entity-based authoring in the editor?
idk. Maybe in Unity 7 or something
#1062393052863414313 would be the best place to discuss
gotcha, thanks for the pointers
i have heard nothing about this but it can definitely be done with custom editor code
really excited for Unity 7, especially with .NET 8
fair point
tbh tho
I would think hard about ecs
its very half finished in a lot of regards imo
yeah, it does seem like that, at least regarding convenience
but the performance gains are very appealing
you can get most of the performance benefits with Jobs
we will get some great gains from moving from old ass mono to modern .net from microsoft
yes
when is this happening i didn't even know it was announced
hopefully before i die
unity 7 should be the first version with the core clr, theoretically there should be an alpha with it sometime this year
what kinda performance improvements should we expect from it?
actually should be launching with whatever the latest .net version is
huge if they make use of span<T> etc internally
yes i just linked that
and it mentions 8
and .net 8 was also the latest version when that was posted
they mentioned going from .net 8 to newer versions should be easier
nice
what changed between net 4 and net 8 to have such a big shift in structure?
the problem is how unity began with mono when .net core (and modern .net CLR) did not exist
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry abt that, give me just a sec
well essentially unity has to use mono to make it cross platform because c# used to be windows only. That slows things down a lot. On top of that the language has gotten a lot of new memory efficient features in the last few years.
https://paste.mod.gg/fdqjfhosrrgm/0
im working on my character controller and trying to get the player character to jump up and away from the wall when jumping while wall sliding, but i cant seem to get it to work. any ideas? also sorry for the awful code.
A tool for sharing your source code with the world!
can you elaborate on what the problem is
gotcha, so net8 & coreclr are multi-platform, correct?
yep
and that's what necessitates the structural rework?
yea cus the engine ofc was created to integrate with monos clr and stuff
its also not built ontop of the .net framework runtime
and i presume il2cpp has some specific things to how mono works too
so its faster
π will be amazing.
In S&box the code recomp and hot reload speed is super fast
also doesn't .net core allow you to compile to native code by default?
I've heard good things about S&box
I'm probably gonna stick with Unity for the time being though
I mostly used it before the massive rework it got (i worked on TFS2)
it is quite nice though and they are making things more "unity like"
Garry doesn't really like unity but they are stuck with it for rust blah blah you can search up
the player character is jumping straight up, which is only half right. i want some vertical velocity, but i also want them to jump outward from the wall theyre on (sorry for reposting the message. forgot to reply)
I remember seeing that debacle lol
I get their frustration, but like, Facepunch will be just fine lmao
somehow this man has had a problem with every 3rd party tool he used for the creation of rust.
story of every software dev lol
like he was trashing the creators of the network solution he used originally on his blog so bad they revoked his license π€£
WHAT
when rust first came out it used some netlib by some company called muchdifferent i think it was called ulink or something like that
it was like the only out of the box multiplayer asset for unity
that worked well for dedicated servers
was that before the old unity networking? (like unity 5 era)
try debug printing the linear velocity on line 119 and see what it gives you when wall jumping
I have fond memories of Unity 4. 1 directional light with hard shadows for us free peeps π¦
im getting velocity outputs, but not actually doing anything
I see
looks like on line 70 you set the velocity to whatever the player is inputting at that moment
so right as your character jumps off the wall, the next frame isWallSliding is false
is there a good way to overwrite that while wall jumping or something like that? i dont want the player to be slidey when walking
what you could do is, while isGrounded is false
make it so that, instead of setting velocity, you add or subtract it
one second
replace line 70 with this:
if (!isWallSliding)
{
if(isGrounded)
rb.linearVelocity = new Vector2(moveInput.x * moveSpeed, rb.linearVelocity.y);
else {
float delta = moveInput.x * (moveSpeed * Time.fixedDeltaTime);
float newX = Mathf.Clamp(rb.linearVelocity.x + delta, -moveSpeed, moveSpeed);
rb.linearVelocity = new Vector2(newX, rb.linearVelocity.y);
}
}
that worked great, thank you.
btw, remember to place ` (three of these, i cant type 3 due to formatting) at the top and bottom of any code you send in chat
and cs after the top `
code blocks
!code explains it better
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you can also add the language cs or csharp immediately after the backticks (on the same line) and it will add syntax highlighting
same here, i only realised after talking in this server more lol
multiply the delta by airAcceleration for that to work
got sidetracked by syntax lol
thank you :)
yup yup!
i learned only a week before first joining this server for the first time
I'm 99% sure there's gonna be no issue, but I figured I'd check w/ y'all. I have a script which creates upward of ~3.5k GameObjects. It only creates them once when the game is started (or I suppose if the player resets), and then the game modifies them from time-to-time when needed. Additionally, it's just a mix of TMP objects and Image objects, so all 2D/UI stuff.
While I've had 0 issue running this game on either my laptop or desktop (both are pretty decent machines), I want this game to be smooth even on a complete potato. Should this be something I even worry about?
Looking up 'Unity too many GameObjects' comes up with people complaining about having tens-of-thousands or even hundreds-of-thousands of objects. And 3D ones no less. Not my measly 3.5k.
Thoughts?
Usually mem is cheap and it is better to preload objects when possible, but the only way to know for sure is to test it yourself on these lower-end specs
Realistically, I don't care that much how long it takes to create them, since it happens once on startup, so long as it's smooth once they're created. I'm assuming that preloading them shouldn't affect that.
just initial load time
while i dont think it'll help to establish a baseline. unity has a ton of useful analysis tools, to find what's causing lag. specifically the profiler
If you want to optimize loading times, you can make a loading scene which you load asynchronously so you don't end up blocking the main thread by instantiating everything at once.
nah, loading times are what I don't care about
It's not so much about loading times and more about making the program unresponsive
you can just limit how many of these game objects are created per frame if needed
Hello, someone have an idea of why it tell me that a GameObject is not assigned, but he still can activate it / desactivate it ?
The variable is assigne in the inspector, but when i try to check if it is assign or not in the script it tell me that no.
void Update()
{
if (!estMenu)
{
if (Input.GetKeyUp(KeyCode.Escape))
{
if (settingsEstActive)
{
Cursor.lockState = CursorLockMode.Locked;
hudSettings.SetActive(false); **//Here**
if (eleveCameraScript != null)
eleveCameraScript.settingsOff = true;
...
}
}
}
}```
And the Settings Object is a child of a canvas
You probably need to assign the hudSettings variable of the GestionSettings script in the inspector.
GestionSettings.Update () (at Assets/Scripts/GestionSettings.cs:77)```
sounds like you have more than one GestionSettings
yeah, didn't though about about that π , but normally the Gameobject that have the other GestionSettings script is disable, so it shouldn't execute the script right ?
yes, but something has woken it up and it sounds like it shouldn't be there in the first place if it's in a broken state anyway
bruh, i had 2 same script, one on the parent, and one on the child, the parent one was empty
Thanks !
script disabled does nothing but prevent Monobehavior functions, it doesnt prevent other methods or awake from running. Only disabling gameoobject does
Sometime we need a exterior eyes on our thoughts x)
Yeah, my bad, the Gameobject which contained the script was disable
Nice it work :)
I have a health bar made up of a border object and a fill object, and I want to make it fade in and out at certain times. If I just changed the alpha values of both spriterenderers at the same rate, you would be able to see a small part of the red fill behind the border sprite during the fade. Is there any other way to do this without having this problem?
i mean, alright, but the mask option should do exactly what you want
https://paste.mod.gg/kzeamcrgbvey/0
I want to add a ladder layer mask that disables my gravity and allows the player to move in all 4 directions freely while overlapping the ladder background objects. I, in my severe lack of creativity and functional grey matter cells, cannot think of a good way to do this. does anyone have any ideas?
A tool for sharing your source code with the world!
Can you clarify because this sounds like two different problems with one being a rendering issue and the other being controls
its entirely controls. when the player is in the same area as a ladder, i want them to be able to move freely
Create a trigger zone that will modify your characterβs rigidbody gravity. Youβd use a separate script and access your characterβs rigidbody using the class reference of your character
where is the ladder part? this code is messy
you need a state machine asap
what is a state machine?
i also had removed the ladder part out of anger
ive made a new one that half works
A tool for sharing your source code with the world!
ive disabled gravity when isOnLadder is true, and now im trying to figure out out to move the character around without them sliding
You need to create a separate script to modify your rigidbody via a trigger zone.
And position that collider where you want 0 gravity
my rigidbody's gravity is already off. im using my own code to handle gravity
i just dont know how to handle movement on the ladder
im still struggling to understand the new input system abit
a bit*
Perhaps constrain your X movement if you want to move only upwards?
i dont want to move only upwards. i feel like that would make it difficult to climb off ladders
Well right before your ladder ends, position the trigger zone just below that point which returns your rigidbody state to normal for a natural transition. You can lerp the transition from RB 0 to your desired scale for a smoother transition
I've got a player and a enemy in 3D space, both have rigidbodies and push/rotate each other based on physics. I don't want them to push each other around, but I also don't want them to completely ignore each other by using the layer matrix.
I also don't want to have to increase both of their drag/angular drag to make them resistant to moving, then having to refactor how they both move and apply very large physical forces to overcome the increased drags.
Is there a simpler way for both to block each other, but without applying physical forces to each other?
you can check in OnCollisionEnter if your player hit an enemy and vice versa and then set the velocity to 0
https://hastebin.skyra.pw/ivecarisim.csharp this script is starting a challenge inside a maze, https://hastebin.skyra.pw/oqemojeziq.java this is in the collider in the entrance of the maze, https://hastebin.skyra.pw/nezeciyara.csharp and this is in the collider in the exit. There`s some collectable objects inside the maze and a counter in the screen. The problem is everytime I enter and leave the maze (turning the challenge on and off) and go in and collect objects, the counter go nuts and count many times one single object collected, and sometimes the challenge just stops in the middle of the maze. How can I fix this?
I'd probably start by making sure you are successfully unsubscribing. It appears this way, but I can't really verify from just the scripts. I can't see what's in your CollectibleDiamond singleton, but I'd first check that it doesn't have multiple subscriptions calling CollectDimond() but that would be my first guess.
https://hastebin.skyra.pw/meceruzuja.csharp collectable diamond script
I'd assume ```C#
private void CollectDiamond()
{
collectedDiamonds++;
UpdateDiamondCountText();
if (collectedDiamonds >= totalDiamonds)
{
ExitChallenge();
}
}
This is being called many times somehow and making your counter go nuts everytime you collect a diamond, since you are calling ```CollectableDiamond.OnDiamondCollected += CollectDiamond;``` on every challenge start.
@marble glade C# var subscribers = CollectableDiamond.OnDiamondCollected.GetInvocationList(); Debug.Log($"OnDiamondCollected has {subscribers.Length} subscribers:");
See what that gives you. After trying to reproduce your bug with multiple attempts of the maze etc.
Whatβs some favorite super basic project management tools yβall use for your projects? I use JIRA for work but itβs a bit more convoluted than what I need for a 1-3 person team. A backlog, task workflow (waterfall is fine), and defect board is all I need
Would be nice if it can link into GitHub
Trello is a decent option, I've used jira/asana professionally, but trello works pretty well and syncs to github.
Thanks that looks good
Ah we used to use Asana at work but we've switched to Linear.
I like how fast/lightweight Linear* feels with the desktop app, and it has a nice/simple Roadmap view to look at your "Projects" (made up of many tasks. Like an "Epic" on JIRA). It also links to Git/GitHub. Trello is a good one for starters though, we used Trello in college
Is that second paragraph describing Asana or Linear
Ah my bad, Linear*!
GitHub has the Projects tab, it's pretty barebones but it might just suffice for a small team.
Yeah prototyping some epics with a subset of story lists would do well, and being able to link pull requests in them the way JIRA does
FWIW itβs just me now but if I get 1-2 other people on board Iβll need to be able to scale to that later on
For now itβs more like a wishlist/backlog Iβm putting together and cranking out
Guys I want to make a grenade explosion that only damages enemies in range and with a clear line of sight (no walls or obstacles in between). How can I set this up?
OverlpSphere then do raycast for each of the found targets / enemies from explosion center. If raycast hits it means it has clear vision
might be better with a capsule/sphere/boxcast if you want not just a thin line towards enemy
not fully working code but the basic idea
void Explode(){
var hits = Physics.OverlapSphereNonAlloc(etc..
for (int i = 0; i < hits; i++){
var col = colliders[i];
var dir = (col.transform.position + offset - explosionOrign).normalized;
var hitSolid = Physics.Raycast(explosionOrign, dir, etc..
if(hitSolid && hitInfo.TryGetComponent(out Enemy enemy)) {
// explode this enemy```
hello, so I have an issue, where I used instance thing so I set a script as an instance and then call it from another scene. However the gamobject I am trying to call is a settings canvas which is activated/deactivated based on button presses. If I start the game in unity and then click play (entering the main scene) and in the main scene I press esc to open pause menu and then I press Options which is referenced to the settings.istance.gameobject.setactive(treu). This gives reference error. But the thing is, if I start game and first open the settings menu and then close. Go into main scene and press esc and then option, the options pop up no issues. How do I fix this?
show relevant !code . as links π»
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thanks π
the script attached to my settings canvas: https://paste.mod.gg/dkbxneezkedg/0
the script in another scene that I am trying to reference the settings menu too: https://paste.mod.gg/chijrvpdugna/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
Lmk if that worked
I did save and copy link
void Awake()
{
settingsScript = settingsScript.Instance;
}```
you should never access `instance` in another script in awake, always access from Start. This gives their awake time to assign the instance
oh I see
also this is called the singleton pattern, its not just "instance" lol
I forgot what it was called, I should have searched for the correct term. I will enxt time
instance refers to the fact that its THE Instance of this object (if assigned correct)
but yeah static make it the only one, but its good its doing Instance check in awake too
This is a problem with how most people initialize singletons, though. There's nothing wrong with accessing another singleton during initialization. The issue is race conditions since everything is initializing in awake methods, but ideally you'd want to have a general provider which you grab singleton instances from, which by itself handles the initialization
So rather than relying on each singleton to initialize themselves, have a general provider that wakes before everything else and have it provide all the instances
A pipeline that Initializes your game before it actually starts is a good idea to have in general
bootstrapper that loads all these up or something
Yep
so a instance manager?
Pretty much
the less you rely on script order and messing with it the better
You know in .NET APIs you also have a main entry point in which you configure your services. You register them, and only after that will it start listening for incoming connections
Right now you effectively try to work around a race condition, but the real solution is getting rid of it
yeah unity is weird you can't really do a traditional DI initialization like you can with other .net frameworks
ideally you do a proper DI anyway and not have soo many singletons lol
Yes, I think Unity could have done better when it comes with initialization in general
Everything just starts at once. They should have had a main entry point like all .NET apps
they kinda do
this did not help to change to start π¦
can you show the error
PausMenu.OpenSettings () (at Assets/Scripts/PausMenu.cs:25)```
this is pauseMenu
nothing to do with instance
If this runs before anything else then it's definitely a good spot to do this in
it is in pausMenu that I am trying to access the instance
ya this is pretty much it
no it should be the one you assign in the inspector, since its public
settingsScript doesnt need to be public if you assign it via instance singleton
If I were you then I would make a single manager which has a GetService<T> method, and this stores the singleton on a general DDOL gameobject
If the script is already on the gameobject, just return that instance
But note there are existing DI frameworks for Unity. Maybe you could use those instead (or combine them even)
DI?
yeah those can get messy too, like zenject
Dependency Injection
Yeah, ideally you can just work without them. Idk if they provide anything
Just a thought. Never reinvent the wheel until you have a working application π
facts at some point OP should learn that, might be confused already with assignment is already what they struggle with lol
I can't assign it in the inspector because they are in different scenes?
correct
yeah I read that prior to asking here
I tried implementing it
monkey
yes you have a singleton for settings, but if your pauseMenu gameobject is in another scene than PausMenu script you need a way to pass that reference.
I am no monkey );
yes you are

please refrain from unnecessary comments especially if they don't contribiute to helping.. I suggest you check the #πβcode-of-conduct
ok
pausmenu script is in the same scene as the pausmenu gameobject
I have main menu, where I have settingsmenu gamobject and a settingsScript attached
then main scene there is pausmenu gameobject and a pausmenu script attached to it
what?
so you want the same object to disable itself ?
yes
if PauseMenu script is on the pauseMenu gameobject then you don't need a reference just use the property
disable and activate
eg cs public void Pause(){ gameObject.SetActive(true); Time.timeScale = 0; isPaused = true; }
But I want the settingsCanvas which is on another scene to activate on the game scene (Main scene) when I press the options button. the settingsCanvas is only on Main Menu scene but has a Don'tDestroy on Load
Maybe I am complicating everything
if settings and pause menu work together why are they in different scenes / heiirarchy and not just one big UI object
with DDOL and singleton
because pausMenu and the Main Menu should not be the same
hmm this already sounds like an over convoluted setup . What is the main menu do then ?
hows it related to the pause menu and settings
Main menu:
Pausmenu:
or should I just dublicate the settingsCanvas onto the other scene too?
and reference Playerprefs settings to same file?
that would work I think
what do you want to do with settings exacly because its a singleton
I don't quite understand what you mean
settingsScript is a singleton
you want both scenes to have access to it no ? isn't that why you made it singleton ?
Yes I want both scenes to have access to settingsScript
