#archived-code-general
1 messages · Page 441 of 1
For JSON serialization of objects, structs in my case:
Does it use
https://docs.unity3d.com/6000.0/Documentation/Manual/script-serialization-custom-serialization.html (``ISerializationCallbackReceiver`)
or would I need to create a custom struct and then convert that into the final struct?
JsonUtility and other json serializers use reflection to serialize a class/struct. Json.NET has properties that can be used to customise the ser/de process.
This interface may work with JsonUtility im not sure tbh.
you can have the first class be MonoBehaviour
then another class inherit from that first class
if thats what you mean
https://paste.mod.gg/qfwicezbtatl/0
this is my wallrunning script.. for some reason, when i walljump (adding force to up and normal direction), the force to the normal of wall is not added properly... the u force works alright but the normal force is not added. it rubber bands me back to the wall. i've been stuck for a week, any help would be appreciated
A tool for sharing your source code with the world!
Do proper logs(make them more verbose so that they don't confuse you or us).
Try draw debug rays to visualize the forces and velocities.
Add more logs(or debug rays) across your code(especially when adding forces and setting velocity) to make sure logic doesn't run when you don't expect it to run.
Hello guys. I am trying to transit the scene from title screen to game scene. I have a intro animation that play at the start of the game scene, which is a combination of couples of small animation, and timed to play one after another. It synced perfectly if I start the scene in the Unity console directly but if I enter the scene by pressing button from the title screen, the animation would become buggy and the countdown sfx would delay by just 1 second. What could be the reason of this? Thanks!
hello
i keep having this error :
'GetEmissiveColor': no matching 2 parameter function at (1)/Library/PackageCache/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitBuiltinData.hlsl(81) (on d3d11)
anybody know fix?
Do you have more context? Unity version? Is it a new project? Any packages / third party shaders that could be causing this?
Not a new project per se
Unity 6
nothing major outside vfx graph (but I think that's included with unity 6)
Working in HDRP
No 3rd party assets
Make sure the vfx and hdrp packages are updated to the latest supported version.
Then regenerate the Library folder
I'll look into this
Thank you
wtf why is it doing this
why is what doing that
we aren't mind readers, we don't know what you're asking about
I have no idea I changed my script, unity crashed, I changed it back and it started spewing random stuff whenever I hit play
it worked fine before
well then it's probably to do with the stuff you changed
but I changed it back so why is it doing this
define "worked fine before"
what do you expect to happen?
where's that logging from?
I have no idea I double click it and it doesn't open anything
and by working fine before I mean the script did what it was meant to do and no random stuff was being spammed in the console
does the log not show where it's from?
are those logs even coming from your code? if not, then you may just need to restart the editor
if they persist after that, maybe try deleting Library
yeah just did that for the second time and now it's stopped I have no idea what that was
probably just an editor bug, if i had to guess i'd say it's likely some corrupt memory or just some pointers that started pointing at the wrong memory 🤷♂️
You know in helldivers when a pod lands next to you, your camera rotates up & away from the crash position?
How would you replicate that using quaternions?
pitch up and yaw away from the direction of the... explosion or whatever
That doesn't help at all.
I'm not asking how to write raw quaternion values. I'm asking how to use unity's quaternion API
or "how to use quaternions from a high level"
but you could get a quaternion from euler angles, and those would be using pitch/yaw/roll
...so why'd you ask about a specific instance lol
have you checked the unity docs on quaternions? that'll be the best resource to see the api
specifically static methods for building quaternions, like Euler (or EulerAngles, i don't remember the exact method name)
lol you wanted something and asked for something else
i pointed you to where you could find info on the thing you said you wanted
if you don't want the help just say so 
What I asked for was pretty straightforward. You saying "just go to the docs bro" and "just pitch up bro" doesn't help me understand the proper way to manipulate a quaternion.
how to use quaternions at a high level, unity's own quaternion api, is described at length in the docs
Nevermind, Just forget it
manipulating quaternions would be multiplying them together or using one of their methods
this is, again, laid out in detail in the docs
docs should be the first resource you look to lol
if you ask about something that's in the docs, don't get surprised when you get directed there
if you have a specific question about a specific manipulation that you don't understand the docs for, then ask about that
just asking about "how use quaternion" will just point you to docs, we can't read your mind for what you actually need. you gotta communicate it.
christ
hey, im just being preemptive here lol. help is a two-way street.
really first thing id do is use cinemachine since im pretty sure it has functionality like this made in. Had to lookup gameplay for this so hopefully i saw the right thing, and it looks like the camera moves in this. Quaternions wont move your object away, it just rotates.
otherwise really you could just define your own shitty version of an animation (or use an animation possibly?). Like a list of quaternions/relative positions and move to them over time. They're still shown as euler angles in inspector, then use quaternion rotate towards or lerp and just assign that to the camera rotation
Sorry yeah, I meant rotate away, not move away
Sort of just a response to an explosion effect. Camera rotates up, but up relative to the explosion
Would rather learn how to work with quaternions rather than use cinemachine or animations
So if the explosion was to the right of me, the camera would tilt to the left
There isnt really much to know about it truthfully. In most cases you'll end up using a few set of methods and then either directly set the rotation or add to your current rotation.
i think for that exact use case you could do something like this
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.AngleAxis.html
then "add" that result to your current rotation which is quaternion multiplication
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion-operator_multiply.html
should just learn to use cinemachine because it's got the impulse listener
cinemachine doesn't scratch my learning itch
also what i suggested above would likely be a pretty stiff movement. im sure cinemachine has more functionality to make it look much better. you can learn without cinemachine but i wouldnt avoid it for your actual game features
maybe a slerp between a start and end rotation would look better but ive never coded something like this myself
is it inherently wrong to plug vector3 rotations into quaternions?
no
if you need to create a specific rotation then you should pretty much always be doing it from euler angles. after its created, you would be doing quaternion math all the way after
Yo whats up I have a specifc question that I'm sure has an answer but I can't find it and don't want to wait for a forum post, when using netcode to program in multiplayer, how can I define a player prefab that includes the character AND the camera that said character needs to use without parenting the camera to the player? The player rotates in such a way that updating the camera's rotation every frame still doesn't make it stay straight, but the player prefab needs a network transform on the player itself to track the position rotation etc, and the network manager won't accept anything other than the object with the network transform and other scripts(network object, network rigidbody, network animator)
cinemachine
I would suggest client side camera if you're new to networking
wdym cinemachine
also yes I don't know why you'd ever have a server side camera that sounds insane
other than like coop games
you don't need to parent the camera with cinemachine, it uses virtual camera components that takes in a target transform
basically the client spawns a camera and those virtual cameras, they get the network player transform -> link virtual camera to transform
does it have smoothdamp easing? I move the camera in relation to the character in the character movement script
it has everything and is one of unity's more popular tools
ah I see that makes sense
yeah I've heard of it just never needed to invest any time into it
thanks
Hi friends, i am trying to achieve hinge movement at runtime by clicking and dragging. when i click on cube with hinge i should rotate respecting the hinge joint, I tried by creating empty object then make parent it of clicked cube, and when object move with mouse cube rotates but this way is not working as i want.
using UnityEngine;
public class DoorDragController : MonoBehaviour
{
public GameObject anchorObjectPrefab;
private GameObject anchorObject;
private void Update()
{
if(Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//Debug.DrawRay(ray.origin, ray.direction * 100, Color.blue);
if(Physics.Raycast(ray, out RaycastHit hit))
{
Debug.Log(hit.collider.gameObject.name);
anchorObject = Instantiate(anchorObjectPrefab, hit.point, Quaternion.identity);
}
}
if(Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out RaycastHit hit))
{
anchorObject.transform.position = hit.point;
hit.collider.transform.SetParent(anchorObject.transform);
}
}
if(Input.GetMouseButtonUp(0))
{
anchorObject.transform.DetachChildren();
Destroy(anchorObject);
}
}
}
Help me please what is this
An error
How can I resolve this
Actually it's solved now. It was just changing some build settings
Try restarting the editor. Does it appear again?
So nvm
No I tried that but it didn't solve the issue.
Not a code question, this is a code channel. delete and ask in #💻┃unity-talk
ohh thanks
I remade my input so it now has a manager, but when I try to jump, it doesn't jump most of the time
Manager code: void Update() { pauseOpen=pauseOpenAct.WasPressedThisFrame(); pauseClose=pauseCloseAct.WasPressedThisFrame(); moveVector=moveAct.ReadValue<Vector2>(); jumpActed=jumpAct.WasPressedThisFrame(); }
Code in the player controller: ```void Update()
{
xInput=inputManager.instance.moveVector.x;
doJump=inputManager.instance.jumpActed;
}
void FixedUpdate()
{
float delta = Time.deltaTime;
checkOtherSides();
checkGround();
angleRad = slopeDownAngle * Mathf.Deg2Rad;
playerControllerFunctions.timer(delta, ref coyoteCount);
if (grounded) playerControllerFunctions.timer(delta, ref lockCount);
handleXMovement(delta);
setGravity(delta);
handleJump();
applyMovement();
} private void handleJump()
{
if (!hasJumped && coyoteCount > 0 && doJump)
{
dust.Play();
hasJumped = isJumping = true;
lockCount = 0f;
Vector2 jump = jumpForce * (sloped ? slopeNormal : Vector2.up);
velocity = grounded ? velocity + jump : new Vector2(velocity.x, jump.y);
}
if (cancelJump)
{
velocity.y *= jumpCut;
cancelJump = false;
}
}```
Hello, I'm trying out photon fusion and building a multiplayer game. Right now just figuring out the ins and outs of the stuff. And making a simple character controller and simple animations.
Now the question I have is, is it advisable to use root animation in online multiplayer game?
I imported fusion's BR200 asset for study purposes and extend upon it. It's using unity's playable API
You have to set the doJump flag to true in Update and false in FixedUpdate.
void Update()
{
// ...
if(inputManager.instance.jumpActed)
{
doJump = true;
}
}
private void handleJump()
{
// ...
doJump = false;
}
Any ideas for how to efficiently spawn NPCs (or any object really) on a navmesh, without overlapping other spawned NPCs in the scene (3D)?
For example, for a simple wave spawn system then spawning x amount of enemies, but ensuring that a spawned enemy does on appear on top of another.
So far my idea is to use Navmesh sampleposition on a random spot around the player and then combine it with CheckSphere to see if it hits anything that isnt the ground layer, but since this is random, it could potentially take many attempts to find a spot with no enemy on it.
Poisson disk sampling algorithm
Isn't that mostly used for static objects though?
You would have to keep track of all the entities as they move around, as you're checking dynamic positions at runtime. It's a bit more overhead and there's no guarantee you'll get a valid location, but otherwise it works the same. You could probably use a compute shader like what Sebastian Lague does for his flocking algorithm to improve performance.
Also, this might help as it's related to your question:
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
In this Unity tutorial, you'll learn how to spawn any object into your scene, and ensure that EVERY single time, they NEVER s...
Yeah there's probably no way around that. I'll take a look thanks
What's the easiest way to disable all player inputs (specifically for a quasi-cutscene at the end of the level to have the player drive away off-screen)? Can I just GetComponent<PlayerInput>().enabled = false; ?
imo probably better to just disable the movement scripts etc.. instead of inputs incase you ever need inputs for skipping or pausing..
easily put multiple scripts in array if you need more than 1 thing disabled
it really depends on how you handle input in your game. There's no one-size fits all.
Not sure if anyone answered this yet, but I would resolve it by taking the distance between my mouses starting location and it's current location, and then based on that value I'd apply the force on that block at the direction you want, and then have it freeze if the mouse isn't moving anymore. Then as the mouse moves you apply force, but if it's doesn't move you don't apply force. This'll help with the constant juttering you get and allow the user to hold the block but still keep rigidbody physics. If you release your mouse, then the block unfreezes and we don't apply force.
guys how do you manage your scripts. idk if im doing it right. i just have a scripts folder with 12+ scripts lol.
is that bad practice or does it not rlly matter as long as it works for me
16 scripts
should i like organize them in folders based on what they do?
up to you i guess, organising them helps you out in future
e.g Scripts/UI, Scripts/Player
As your project grows it will be helpful to organize your scripts into folders and namespaces based on functional areas.
For example I have a folder for things related to my menus. Another folder for things related to the combat system. Another folder for the game data model, another folder for the save/load system, etc..
My game project is going to need a fairly complex dialogue system
Multiple units, some static and guaranteed like bunkers, some instanced like scouting units, can have dialogue
The dialogue can be set firm and need to wait for flags (story stuff) or generated (orders for a bombing run or warnings to enable point defenses)
I'm trying to figure out the best way to organize and manage dialogue and conversations, and doing so that past transmissions can be re-read in the archive
My first thought is to create one script per static, permanent installation/unit and one script per generated unit type that holds the dialogue in lists and static variables for accessibility
So the main manager runs the code to generate the event list for the day, randomly rolls "Bunker 4 orders a strike," passes that info to the radio, the radio consults bunker4Dialogue.strikeOrderLines[random] and sends the resultant text string to the output box to be read when the player checks their radio
this is mostly a sanity check, this is my first time handling a system this large and complex I wanted to make sure I didn't overlook something much simpler or better
Theres typically 2 common ways projects organize their files, either by "feature" where related files like models, sounds, prefabs, etc are grouped with the scripts in their own sub-folders, or by "type" where you have a "scripts" folder for all your scripts, a "models" folder and so on: https://unity.com/how-to/organizing-your-project
Personally, I prefer the former as its more specific and convenient having all the dependencies a script might reference in the same parent folder instead of trying to remember names to search the project with
thanks 😄
Has anyone experience with floating RigidBody characters for movement? I have this script that floats my character (mainly to make the landing smooth so I do not just hit the ground) but because of gravity probably it never settles at rideHeight and that interferes with jumping mechanics. I have a RayCast at the lenght of rideHeight for finding the ground. Any ideas how to fix this? https://paste.mod.gg/tsvbnjjpxqzi/0
A tool for sharing your source code with the world!
im having trouble with firestore which doesnt support unity types like int, float and vector. i have to convert everything during serialization and deserialization. is there a better solution like a nosql db that supports those types or an easy way to convert the data?
so, I would suggest inverting the responsibilities here
instead of having the units know about their dialogues, turn it into configuration for the dialogue system instead
this configuration would be some kind of mapping of unit ids to their dialogue lines (scriptable object, json, whatever works for you) and a centralized place for working with it (everything will be in the dialogue manager, not distributed between units), which should make it easier to replicate the lines to the "radio" or whatever else
the reason for this it to decrease the coupling between the units and the dialogues, now the units don't have to know anything about the dialogues anymore, which should make things more scalable
Int and float are C# types though. Not unity.
And generally most programming languages have these types.
I know, unity uses c#. the problem is that the firstore sdk automatically converts them to long and double but heres the thing: not if they are stored in object fields, the remain doubles/longs. so im now trying a generic type interface as type in order to keep flexibility but keep the types
I'd assume that there is some wrapper for unity that should make it easier to work with it. Don't quote me on that though.
Best thing i found was the firebase sdk which does the conversion although it doesnt support vectors and had to make my own. Mongo supposedly supports all of them but have to write a ton extra code for converting
If you can, consider your "static" unit as "instanced" unit. It would reduce the complexity.
Utilize EventChannel to propagate whenever a dialog is said. By example, if you have localize dialog such as in between unit, you can publish an event on the channel. And if you do have "system dialog", you can still publish on the same channel. Make it transparent to whoever needs to listen/archive. (As a bonus, if you have other system that needs to listen to dialog they can use the same exact channel)
Centralize all your dialog into a single script. It would be easier to manage if you want to batch process them either for localization or search specific dialog.
Hello everyone. I'm creating an abstract MonoBehaviour derived class that acts as a middle man between monoBehaviour and final components. So my components will derive from this middle-man instead of monobehaviour directly, kind of NetworkBehaviour in netcode. I need some code to run on Awake on this middle class, but I run into the issue that I don't want to prohibit derived classes to use Awake, and I also don't want to force derived classes to call base.Awake, which leaves me in a very awkward position where I'd have to manually call a fake awake method on my middle class, but I'd have to perfectly match unity's native awake call, so I'd have to call this when the scene loads, when an object is spawned... Is there an elegant way to have another awake call without shadowing a derived component awake? (The same applied for the other magic methods like onEnable or start, I don't want to shadow any of these)
Nvm, I already require another component to attach this middle class anyway so I'll run the awake from there!
No, there is not.
And using a "middle class" like NetworkBehaviour is not a good pattern.
What do you propose instead?
It depends what you want to do.
you'd need to call base.Awake() from the extending class
and I also don't want to force derived classes to call base.Awake
ah i missed that mb
No worries, kind of a dense essay xdd
Tbh, I was making my own networking system so yeah, pretty much my networkbehaviour is in charge of creating and managing the component's Rpc calls
I could centralize them, yeah, but I still want the diferenciation between networked and non networked components
In that I case, I'm not exactly sure what you could do. Instead, I can say why it is a bad idea so you might atleast protect yourself.
If you create an intermediate class such as "RegistrableComponent" which is not necessary a NetworkBehaviour, you then find yourself in a ackward spot when you want to have both ("RegistrableComponent" and "NetworkBehaviour"). You cannot inherit from both.
So, if you are creating a library, whoever is using it (even yourself), is force to live with the choice you made. Which is a bummer.
Well, no, but in this case wouln't I just derive RegistrableComponent from NetworkBehaviour? If I really wanted non-networked behaviours to also be registarable I could do the reverse and inherit NetworkBehaviour from RegistrableComponent
can't you just call your "fake awake" from the final point of you accessing the real one?
That is true, from a library point of view I do get what you mean
Then all your RegistrableComponent must be NetworkBehaviour, which is definitely not what you would expect from a RegistrableComponent.
You can't have base classes call the same method as a derived class, if a derived class were to use the awake method it would shadow my one. However, as stated, I already solved this problem by proxing the awake to a dependency of netwrokBehaviour (NetworkObject)
I mean I guess I would force library users to create a dedicated component to do the registering. Which is something I can live with, since I do belive in making every component as low responsability as possible for maintainability, and if a component is in charge of networking code, in my opinion it should just stick to that no? I do unserstand you, however I don't think It's that big of a deal
couldn't you just seal that off though? eg.
abstract BaseClass
virtual void Awake
abstract MiddleClass : BaseClass
override sealed void Awake
OnAwake()
virtual void OnAwake() {}
MiscClasses : MiddleClass
well yeah, but then u are stealing the awake from the derived and forcing it to use OnAwake, which is non-standard
I did explain in my original message that my issue was that I did NOT want to "steal" the unity magic methods
But again, I already solved that, thanks tho!
ok
Yes and no. Sometimes you might want to add other helper functionality to your class. Dependency injection, for example, might want to use the same approach you did. It is irrelevant from the actually responsability of the class.
I guess yeah. I mean at the same time, almost every big networking library (That I know) uses this or a very similar method, so in the efforts of keeping integration seamless (by not shadowing), while maybe not the smartest way to implement network stuff, NetworkBehaviour is a well known and proven way of doing it no?
It's just In my case I created a unity-like very very small engine and my networking solution, instead of being server and client mixed, it works with unity for the client and the small engine for dedicated servers writen as pure dotnet console apps.
People that made NetworkBehaviour are human as well. They choose what they believe was the best approach, it does not mean it is the best approach. It definitely works, but it has the draw back I just said.
100%
It's not release ready yet, but I think I'll be able to release it fairly soon, I think it's a very neat solution for people like me, that while liking the netcode-like flow, don't particularly like having server and client code mixed.
Thanks for the insights @steady moat
For my LeftStick Input Actions Binding, I simply could not find an option to replicate GetAxisRaw, and so the closest I've come is by code: csharp void OnMove(InputValue inputValue) { Vector2 inputAxis = inputValue.Get<Vector2>(); inputAxis = new Vector2(Mathf.Round(inputAxis.x), Mathf.Round(inputAxis.y));
But, I'm sure the Input System has an official way of doing this, right?
inputValue.Get<Vector2>() kinda is the equivalent of GetAxisRaw
also, #🖱️┃input-system
guys I'm trying to make a working pc in my game and I'm testing the function to drag icons in the desktop, but when I release an icon, it doesn't fit the grid layout I've put in the panel (compare its position with the rest of the icons)
check my current script: https://paste.mod.gg/axyyjfkoydnk/0
A tool for sharing your source code with the world!
What do you mean by that first sentence?
Are you saying I should generate all the dialogue handlers at runtime, rather than having the static ones hardcoded and the instanced ones generated at runtime?
The second idea is really good, thank you very much for the advice
It's much more future proof than my initial concept, and will make possibly implementing a feature on the "maybe if I have time" list (intercepting enemy comms) way easier
Thats a really good tip, thank you
part of the reason for the decoupling is that a large portion of the game involves using codes, ciphers, and various systems to obfuscate and decode information, so I'll have random weights determining which of the methods will be used for a particular bit of dialogue
so plaintext gets sent through a substitution cipher, then a SIGABA code, then finally output to the player, for example
I want replayability and variance, so I'm going to use randomness in which methods and what keys are used, this will also change which physical gameObjects will trigger and print/signal the information
If a message is rolled to be morse code, it needs to be converted and signalled, but if it becomes teletype ciphers, it needs to be sent to the printer to be instanced physically
on the subject of json vs scriptable object, does either have a particular advantage?
I've been doing more research and there doesnt seem to be a clear winner between json, scriptable object, or even just writing out string variables in large arrays
I want scalability, so I don't think I'll take the lazier option even though I'm a solo dev and the "easier for non-programmers" aspect of json doesnt benefit me
I meant that instead of having two system that risk to be different, try to come up with a way to use the same code path for both.
By example, you might have "Building" that are preplaced in the map. They could still call the same function as the "Unit" in the map. DialogSystem.CreateDialog(string dialog, DialogType, etc...)
That makes sense, I'll try to do that, but it may end up being suboptimal
With the current plan, static buildings will always come in through wired systems and an operator board, and instanced units will always send messages through the radio transceiver
It couldn't hurt to attempt it that way, though, and it'll be easier to split the functions later if needed than merge them if I end up needing that instead
most of the time this is just a matter of ease of authoring
if you choose to place everything in a large array you'll need to recompile your project on every change, increasing iteration times and also coupling your code with your configuration
you can solve this by providing configuration from an external source (scriptable objects, jsons, csv, etc.)
scriptable objects are fine inside of Unity, but it gets complicated if you want to modify them in bulk or author the data outside of Unity, like in a spreadsheet
json is just a popular format, it's human-readable, easy to modify and it's not coupled with Unity, so you could generate it from somewhere else and provide it even during runtime
I would suggest trying scriptable objects for this, then you can figure out the pros and cons later
How broad would you suggest I go with the scriptable objects? One that can hold everything? Seperate it by sender?
The reason I ask is because there will be fairly large amounts of unique dialogue for each type of sender, but there will also be a lot of shared pools, like the one to generate firing orders, where a dynamic message will need to be generated based on a lot of game state information, with the prewritten sections gluing the line together.
ScriptableObjects apparently are not easy to modify at runtime from what I'm reading, for cases like that where I need to glue several peices of game information together to form the line it seems I might have to make an exception and handle them differently
you can edit scriptable objects in bulk in editor easily, asset database to load em, modify and set as dirty ✨
that's easy for programmers, non-technical game designers not so much
why not just using Json ?
it's hard to suggest anything specific without knowing a lot more about your project, maybe you could have one scriptable per unit containing all their messages and then link them under a common scriptable responsible for holding all the messages
I would not modify them during runtime though, your dialogue system should be responsible for generating the messages according to the configuration (scriptables) and parameters provided by the game state
JSON is good but scriptable objects will deser faster
I doubt very much it would be noticeable in terms of performance, unless you're talking about many megabytes of jsons
true, one the benefit of Json(files) allows you to add onto it besides inside unity editor. Maybe even a custom editor just for dealing with dialogue addition of new lines etc.
depends ofc how complex you wanna go
One factor I think might change which is better, though at the moment the scriptableObjects are seeming like the much easier option to create the dialogue pools
I want to have an in-game archive of messages and conversations
the time and date the mesage is received will need to be recorded, as well as which decoding method was used, all of which are variable and will change on different playthroughs
This means saved data
Would storing those as JSON files be the way to go? If I need to use JSON to make the archive entries, would it be easier to just always use JSON, or would that be unrelated?
Scriptable objects for the pool and json for the saved files seems like the easiest solution
I would go with json for the data storage, yes
Does the JSON Serialization from the serialization package support native types? That isn't mentioned anywhere in the manual
Guess not.
Yea I'm not surprised it's not, you can use another serializer and make a converter to fix this
why is destroying game objects and recreating them so disastrous to performance, is it the reallocation of memory?
garbage collection
I want to know why the garbage collector causes a performance hit 😂 not sure where to find that info. Just pure curiosity is all
Because it's not free to do garbage collection
it's an actual process the computer has to do
And while it's doing garbage collection, it's not running the rest of the game
unless you use ECS, right? i wonder how ECS does it
ECS doesn't deal with managed objects at all
it completely bypasses C#'s memory management scheme
it's back to the basics of manually allocating and freeing memory more or less.
so it freely allows you to instantiate and destroy as often as you want, without having to do object pooling?
no
WE're basically talking about completely different abstractions so it's hard to talk in the language of Instantiate and Destroy in the world of ECS
you're basically always using native buffers and absolutely using and reusing the same buffers in memory
which is similar to object pooling
Basically we're stepping outside the world of Object Oriented Programming for the most part in ECS
is this what c++ game engines like Source do?
Native buffer kindof just sounds like a more primitive type of list of objects
source is not ECS style in the slightest
What does ecs mean
but it does do a bunch of custom allocation and uses memory arenas often
Source is just written in C++ which doesn't use garbage collection to manage its memory
entity component system
does source handle this stuff better than unity with ECS would?
no
@night storm your questions are comparing apples to oranges
C# does - hence the garbage collection
GC handles the memory for you, which makes many things easier but it comes at a cost and means less control over memory
Does Unity just build onto some abstract classes or something to make the garbage collection work for objects?
object pooling in a garbage collected language is sort of like preventing the GC from collecting memory so you can reuse it later, which is cheaper.
Only the C# half of Unity objects are garbage collected. The native half of it needs to be managed manually or by the engine, hence the need to use the Destroy function.
I haven’t worked in c++ yet much or with any garbage collectors and I sortof want to learn how they work
its just how the runtime works anything that allocates it checks during garbage collection to see if its still in scope
Oh cool
like in C++ to make a object you need to allocate memory for it, then would need to decide how and when to cleanup that memory
GC finds when memory is no longer used for you
Do you think it’s more efficient than C# because the program knows when to cleanup without stopping the whole game?
define efficient
The garbage collector analysing objects to find what to delete has a cost
Instead of searching a ton of memory, it searches the pointer you stored in code and de allocates it?
thats what GC is doing
but if this was C your would have to write code yourself that de allocatates and choose when and where to do so
It stores pointers on its own?
and could leak memory if you failed
Right
Hey guys! I just replaced my character from a capsule placeholder to my actual character. although the capsule was working perfect, the new model (although using the same exact scripts/etc.) doesn't rotate how it should, or how the capsule did. Although the new model moves and strafes correctly how it should, its not actually rotating front facing depending on what direction its going - unlike the capsule which DID do that. so im not sure what the issue is. Although im pretty confident the code isn't the issue, ill post it anyways (the bottom part function is just how i apply VFX effects to the character which is non affected)
https://paste.mod.gg/sudbagnhwzfb/0
thanks 😄
A tool for sharing your source code with the world!
i dont know anything about what either of them do under the hood, i know that you can spawn and destroy stuff a lot in source without any visible performance impact though, to the extent that would make default unity lag due to the garbage collector. would ECS be able to be as efficient as source in that regard? or would it use up more memory or something
memory allocation/freeing is not free but will be faster than GC processing
ECS is a totally different approach to things, i would not choose it purely on GC costs
also there are many many ways to avoid GC costs just by doing more reuse and structuring things better
Let's say your program is like:
class A {}
A a = new A(); // we made a new object
a = new A(); // we maade a second new object. But what about the first one? It's an orphan now
In this example the first object we created is sort of lost to the void. It can't be used anymore by anything but it's still taking up memory. The garbage collector's job is to find object like that and get rid of them. The problem is, to do that it needs to basically look at all the references in the program and make sure none of them are pointing to the object. That's an expensive task. There are some optimizations but in general it's expensive. It also then needs to rearrange and recompact the memory and sometimes move objects around for example so it's easier to use the remaining free memory.
If this was C++ or something this would be a memory leak.
well the reason i'm asking is because if i want to instantiate and destroy a lot of things i would need to make an object pool for each of those, and everything in the object pool stays there and takes up memory all the time, whereas source engine probably cleans it all up immediately. i was wondering if ECS was able to handle it like source without having to make a bunch of object pools
Source engine doesn't clean anything up automatically
you write your code in C++
you are responsible for the cleanup
you do know soruce is pooling things often as well
Also if you are going to reuse that memory later it's wasteful to clean up the memory just to reallocate it later
or making use of arena allocators to clean stuff up on different lifetimes based on what allocator was used
pooling has always been a thing used often in games
weather that be pooling actual objects that do something or memory
what if someone shoots 1000 bullets at once and then they get put in the pool but most of the time the player shoots only like 20 at once so now there's 980 disabled gameobjects in the scene that don't get cleaned up, and destroying them would cause garbage collector lag spikes, how would this be handled properly?
In ECS you could say everything is pooled by default - because all components go in contiguous buffers that get used and reused over and over again
If your game can handle 1000 active bullets at once then it can certainly handle 1000 disabled bullets
generally you'd just let the memory be used by the deactivated bullets
it's not an issue
memory is cheap
most would impose a upper limit they keep pooled
I'd be more worried shooting 1000 bullets at once, pooling wont help you there
You could have an upper limit but if you frequently break that limit and then have to deallocate again then you're essentially operating as if you had no pool at all
also its common for a lot of pools to grow as needed
then only clear out during a load or something
where the GC spike does not matter
You would ideally clean up the memory at the point that you are certain you won't need it anymore.
Which is extremely bespoke to your game
if you could afford taht once you can afford it for the rest of the round or level
hmm alright
but ECS would make it way better i imagine, so the ideal scenario would be to just handle all these bullets with ECS?
I see, that’s a good example, Thankyou
i feel you are missing the point and expecting pun intended "magic bullet" soultion
like i would not choose GO's or ECS based on this alone
since there are easy to understand soultions to do what you want in either
Is the source engine any good? What can you even do in it
well it was very good for its day but rather dated now, also is not a off the shelf engine like unity
there are rumors future ecs will be created auto into unity from GOs
its just the engine used for half-life 2 and other valve games, its a terrible idea to use it for your own games though
maybe but i do not see all benefits from it being possible if they use that approach
alot of its benefits really involve you designing with it in mind
Compared to what we have today its not good, there are so many things not publicly documented 😐 I have to ask others who know the engine well for basic stuff
e.g. there are different ways to get the current map name in source for client and server and they don't even return the name the same way
its still very much a inhouse engine does not have anyhwhere near the support untiy and unreal do and the docs
Yeah the execution is different for sure... Wish I had the link to the UnityTalk when they explained some new ECS stuff where they mentioned this.. I didn't mean a total conversion but from my understanding making a bit more streamlined, where basically you can get benefits of ecs with the ease of GOs
A lot of the useful dev documentation is internal and only avaliable to partners which im not. And those I know who are cannot just share it.
Thankfully I can ask questions and they know source very well so can answer most stuff.
Source Engine was created for specific development from Valve not a general availability engine
yeah had similar problems with goldsrc back in the day, feel i only figured out most of it due to idtech 2 experience
Source 2 is probably very much up to date with features but only they know internally what those are..
well facepunch got it and basically re did half of the engine to be like unity 😆
alright thanks for the help!
by the way, how does unity handle it when the player is able to go back and forth like in half-life between 2 levels, in unity it would have to create and destroy the scenes repeatedly, if the player goes back and forth a bunch of times and then keeps playing, wouldnt the game keep lagging a lot for a long while due to garbage collector now having to clean up a hundred scenes? each scene containing tens of thousands of objects
hl2 would hitch from that too btw
would pop up loading for a bit
Unity you can do additive , HL2 does not
also there are ways to load in parts of levels at a time
"native" objects like meshes and textures would be unloaded right away or when requested by you/addressables.
but would unity clean up all the garbage during the loading screen or would the new level load and then it keeps gradually cleaning up the garbage while the player is playing?
yes you can instruct it to do so
also it does it already for most of the scene stuff being unloaded
would it make the loading take way longer though?
The GC for the most part just does it whenever it thinks it's time. Unloading a scene often would trigger it but not necessarily.
it depends
if you already have a loading screen for it not really
You can test all of this yourself btw, run your game with the profiler and see what it does
like GC adds little hitches and stuff
no one will notice or care about that during a loading screen
yeah its fine during a loading screen, i was just worried that it would start cleaning up the garbage after the loading screen, during gameplay
also you keep comparing to hl2 i take it you never played it on release on the type of hardware popular at that time
the loads between scenes of larger levels were fairly long and happend often
was also a bit of hitching after getting into the new scene
the game had about 21 years to get optimized the way it is lol
gotta appreciate valve always dropping updates though to keep up
you deal with problems as you hit them and they become important
hmm yeah that makes sense, thanks for the help, i got much smarter with this conversation 😄
if it becomes a problem, you mentioned instructing the garbage collector to do its job cleaning up the scenes during the loading screen and not afterwards, how would that be done?
experiance will guide you into making better decisions early on, but even then there is still always multiple passes on everything as different things become priority or problems show them selfs
a turn key solution that works for all is rare if at all existent, each project has its own problems to be solved.
GC.Collect though i would only use it if there is a need
it would not be needed in many cases especially around loading anyways
for reference i have used it only a handful of times in my whole career
since i never had need otherwise
since i could solve the problems with other approaches
this is why unity has their incremental gc (its configurable too!)
You could also have a Loading Scene then Unload/Load each scene additive separate, GC should already kick in now ? (gameobjects get destroyed when scene is unloaded)
i have never found GC stutter to be a issue for me even back in unity 4 and 5
can be avoided by just putting thought into when things load and unload, and avoiding per frame allocations
I think my game allocates ~100 bytes or so every second during gameplay. It used to be 0, but some weird allocations have been showing up since a Unity update that didn't make any sense, so I just chalk it up to editor profiling being weird.
profiling the editor is not all that reliable i only bother to profile builds
100 bytes every second or so is not going to really hit things hard
Yeah I'm fairly certain it's just some editor profiling weirdness, since IIRC it told me it's value tuple constructor that's allocating which makes no sense.
But ~100 bytes per second is so low that even if it was real it wouldn't matter anyways.
yeah last time i had that, it was a update to our networking lib and it started doing extra logging
really find eventaully you just stop thinking about a lot of this and write in a way that is good by default
Oh lol
Guys, how do you learned to code
I went to school for it
but, to learn code in unity, c#
Once you know one programming language, it's easy to learn others. I was an expert in Java already, and had some C# experience from an internship.
I also took a game dev course in college, though I used Microsoft XNA for that, it's also in C#.
Most of Unity itself I learned through trial and error and self teaching.
basically years of trying to make stuff and failing.
But slowly building up a corpus of knowledge and experience
Either go to school for it or try to learn yourself from online resources such as https://learn.microsoft.com/en-us/dotnet/csharp/
It will take you a long time to get good at it.
Is there a way to force a character controller to recalculate its collisions? I'm using them in a VR game and adjusting the character controller's center and height to match the player's head position, but if a player moves their head into a wall the character controller jitters trying to push itself out
However just walking into a wall with the character controller obviously has no jitter
I would also personally suggest w3schools C# course before starting Unity: https://www.w3schools.com/cs/index.php - it covers all of the basics, in lessons that you can test out like a "code sandbox" for practice - when you get familiar with the basics, you can try to challenge yourself with their examples or look up/create your own, for example instead of just completing the "variable" topic or the "methods" topic, try to make a calculator or some other challenge that uses multiple topics at once - you may either find it trivial or surprisingly very difficult to actually put concepts together despite understanding the concepts independently
When you do become familiar enough with the language that you can do some small challenges with those topics, then I would say is a good time to try to step into Unity Learn Pathways which will teach you how to use the engine and how to use C# within the engine (it wont really teach you C# itself very well, which is why I suggest w3schools and the resource Praetor provided), as Praetor mentioned, it may take a while, but so does learning any skill
I dont get this? ive used a simple technique to rotate the "weapons" while the player (the square) is holding them where u just take the position of the weapon and the position of the mouse and do some trig to figure out the angle between them. The only problem is that when i do print(transform.rotation.z * Mathf.RadtoDeg); it prints a value that dosent make sense. When i manipulate the objects in the scene rotations work like in the unit circle (the printed value should be 180 or 0 but its 57?), but then the value is different when i print it? I understand if this is a hard question to answer because it might be something with my code but im wondering if anyone has any ideas
Don't read the individual components of a Quaternion. xyz and w are for advanced use cases only.
TLDR: transform.rotation gives you a Quaternion, not a set of euler angles. You should not be ever looking at the individual bits of a quaternion pretty much
ohhh i thought a quaternion was just the euler angles but with a w at the end
nope if you want to use euler angles with it, you can use AngleAxis, Euler or one of its other helper methods depending on what you need
thanks so much it fixed my problem
i have billy and his box collider here, i also have a death animation for billy. do you know how i can get the animation to play and destroy billy after the ghost presses a button in range of the box, ive been trying and i just cant get anything to work.
Show what you've managed so far
right now this is all the code together, i deleted all the other stuff because it would cause problems
Well, I suggest looking up tutorials on how to interactive with other game objects using their colliders. This is usually done using OnTrigger methods using a kinematic rigidbody. You'll find tutorials on how to collect coins, ect using similar logic which is what you'll want to use here to 'press' the button
You've also have the option of using raycast/overlap to immediately check locations for colliders.
Thanks!
Hi there,
I'm having an issue with other objects pushing my character controller even though no rigidbody is attached. Heres the code
using UnityEngine;
public class charMove : MonoBehaviour
{
private CharacterController characterController;
public float speed = 5f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
Vector2 move = new Vector2(Input.GetAxis("Horizontal"), 0);
characterController.Move(move * Time.deltaTime * speed);
}
}
do the circles have colliders?
CharacterController provides collision logic out of the box
Well, nothing too developed like rigidbody collision, but it provides a simple grounded implementation
I know context is needed for a proper answer but just a curiousity/vibe check from more experienced devs, Do you guys ever run into situations where involving the specific type of a class (outside of direct typechecking/casting) is a reasonable part of a solution or is it pretty much always avoidable
if you don't want that behavior you could use a Kinematic rigidbody + MovePosition where colliders don't affect it while move. Colliders always affect character controller during move, here also sphere and the Step offset.
why does c# have to be so difficult this shit doesnt make sense
i put 3 lines and i get 7 error messages 💔
#💻┃code-beginner
make sure your !IDE is configured so you don't make basic syntax errors. and maybe also consider learning the basics of the language before attempting to learn unity
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
anyonje run into this issue when trying to bake Adaptive Probe Volumes
Baking Set-Default.CellProbeOcclusionData.bytes' does not exist
@dapper schooner Don't cross-post. And this is unrelated channel.
They have circle colliders but no rigidbodies
Should I be keeping it enabled?
Not sure what you mean. If you need some semi-created player controller that deals with collisional feedback then use the CharacterController or Rigidbody, otherwise you can always just move them transform in update
does anyone know of a way to generate menger sponges with a large iteration count without hitting single digit frames? I want to use it for procedural world gen 😭
generate what??
Oh, I see.
Well, how are you generating it now?
https://pastebin.com/9LYxyPVt
This is how I also see most people doing it, but needing it to be large scale causes a lot of issues performance wise
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.
Did you profile?
No but i already know the issue
the triangle count scales exponentially
Well, one thing that could be a cause is GC pressure. So you really should start with profiling
cubeVertices cubeTriangles being created anew for each iteration is a pretty bad thing
Beyond that, you should either think of multithreading or compute shaders.
Generating it async is an option as well
its not just the generation i'm worried about, its post generation. With 4 itterations I end up with 3.9M triangles
Yeah, if you are going for something like infinite scale, you might want to draw it in a shader with path tracing or something.
it needs collision though, its supposed to be the terrain
or rather ray marching
whats that?
Well, then you gotta limit the scale
what if I just had a prefab that changes its itteration count depending on how close the player is to it and then had multple of them kind of creating an LOD effect?
That might work I guess.
If it doesn't need to be generated procedurally, just generate several LOD versions of the mesh and reuse them
Could even do some GPU instancing
that's a good point, i'll experiment with that
is using chatgpt ,cursur,deepseek and grok AIs is better for my unity game evrything!!by copy and paste the codes !!?
not using them is the best for your unity game
why!?is there any problem!?
If you're asking these questions, you probably shouldn't use them yet. Learn the basics, get some experience. When you know what you're doing, you'll know that what tools you can use and how.
i am using them from 1 month!
Great, then what's the point of your question?
should i drop them and learn from my own!?ist it would be much harder!?...
well yeah it would be harder because you would be doing the work
learning french is a lot harder than chucking some words into google translate in the same way
it would be beinficial for me !?btw my agee is too early for these things!.......
Yes, you should learn the basics properly. Whether you use ai to assist you in that or not is up to you, but many people would recommend against it.
If your too young to learn how to make Unity games then you would be too young to make Unity games
This discord won't help you if you use AI generated code
but first where to learn even the basics!!??and work them in my unity game!its my first and last ame of my life which i also want to finish in 1 year max!....as from my planning!!
Well, you don't want to be dependent on ai. You need to be able to do stuff on your own. Imagine if your country bans ai suddenly or world war 3 happens and humanity is pushed back to the stone age. There's gonna be no ai.
You can learn the basics by following the beginner pathways on unity !learn:
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
fair enough,but it never gonna happen!....
@cosmic rain u mean first learn everything about c# then touch your game right!?....and that bot's link will teach me everything about c# and i become a proffesional master!!!?
what if i !?.....
but this is my first and last game so,,....
your in this server for advice
this is the advice
if you don't care about the advice
¯_(ツ)_/¯
how much it had been on unity!?
years of experience
of you!?
so i an take more
experience from u !
?
Something like "professional master" is arguably unachievable. There would be always more things for you to learn.
But if you at least know the basics and have the correct mindset you can keep on learning more while also working on your project. At that point it's up to you, but I'd recommend not setting too high of a goal as a beginner.
but imma learning c# first then thinking to learn python,Java,html then javascript then c++....is this is the route towards hell!!??
Why all these languages? Weren't you going to develop a game in unity? Is that not your goal?
To answer your question: it's not too difficult to learn all of these things in a few years. It's just very unlikely that you're gonna be using all of them at the same time. And people tend to forget and get worse at things that they don't do regularly
its my first goal then after that my expansion of goals begins!!..
i mean after learning this all before i turn 18 ,,btw imma is 14-15 yo rn......after that my own AI
is this really better option for my life!?or crazy enough!?
I don't really see the point of such goals. You should probably focus on one thing.
If you're only gonna know many things on shallow level you're not gonna reach any success in anything.
yep first unity and c# then my own something real by python and javascript or java then again by c++ and HTML
if i tell u myreal goals...
What for though? I don't get it.
is first make a unity game by c# in first 6-8 months then my own link while building my app with that in 1 year then again make a app but by unreal from c++ before 18......
u understand!!??
sorry a game from unreal...
Not really.
If you keep switching like that you're only gonna create very simple stuff that doesn't have any value.
after 18 my own buissness by that all money.........
Or even not finish any project at all. Drop them in the middle.
then what should i properly do!!?
but i never ever give up!!!!
NEVER
I don't know. I don't understand what your end goal is. Is it making money or something?
give up wasnt even a thing'
my goal is bigger much bigger than elon itself.....but possible
Okay, at this point I feel like you're just trolling.
Anyways, this is not the right channel for such conversations. Do you have an actual question related to coding in unity?
imma not trolling just didnt want to exposed it in online infront of everybody...
can u please tell me whatshouldi really do
You can do whatever you want.
What exactly do you expect me to answer?😅
For me these goals sound unrealistic. At least not in the time range that you specified. And it's still not clear what your actual end goal is.
And I'm sure most people here would agree with me.
Anyways, this is not the correct channel for such topics. At the very least move to #💻┃unity-talk
getting around 600 fps with this, thanks for the suggestion!
thats do what seems impossible rather than possible buddy!!!..
anyways the time and me will decide by my work
more rest is not equal to dream,,,,less rest and more work= execution!!!
Would I be able to use raycasts to detect collisions with a rigidbody?
I’m using the Unity char controller already. Im confused
I'm trying to write a script that feeds in some information into a SpriteRenderer's UV1.
float minU = 1;
float maxU = 0;
float minV = 1;
float maxV = 0;
foreach (var uv in spriteRenderer.sprite.uv)
{
minU = Mathf.Min(uv.x, minU);
maxU = Mathf.Max(uv.x, maxU);
minV = Mathf.Min(uv.y, minV);
maxV = Mathf.Max(uv.y, maxV);
}
var uv1 = new NativeArray<Vector2>(spriteRenderer.sprite.uv.Length, Allocator.Temp);
for (var i = 0; i < uv1.Length; i++)
{
var uvactu = spriteRenderer.sprite.uv[i];
var u1 = Mathf.InverseLerp(minU, maxU, uvactu.x);
var v1 = Mathf.InverseLerp(minV, maxV, uvactu.y);
uv1[i] = new Vector2(u1, v1);
}
spriteRenderer.sprite.SetVertexAttribute(VertexAttribute.TexCoord1, uv1);
What do I need to do to make it so this code runs whenever the SpriteRenderer readies a new sprite? This includes in the Editor. Like whenever a new sprite is set.
It's more of an architectural question rather than specific to general scripting in Unity, but what is the way of storing RUNTIME data between components in modular architecture with heavy composition use?
For configs/static data it's easy - just use SOs or/and JSON serialization, but what about runtime data which changes all the time? I feel like I'm fighting Unity with this, because I don't want to store data and logic in MonoBehaviours and want to separate them. Any tips on this?
Yes of course. Raycasts don't care if you have a rigidbody or not, they seek colliders that's all
what kind of data are you trying to store? sounds like you could just use plain c# classes
void Move(int Ground)
{
if (!isChargingJump && !justJumped)
{
float targetSpeed = moveInput * moveSpeed; // Maksymalna prędkość
float currentSpeed = rb.linearVelocity.x; // Aktualna prędkość
if (Ground == 1) // Normalna ziemia
{
if (moveInput != 0)
{
currentSpeed = targetSpeed;
}
else
{
currentSpeed = Mathf.Lerp(currentSpeed, 0, Time.fixedDeltaTime * 2f); // Wolniejsza zmiana prędkości
}
}
else if (Ground == 2) // Śliska ziemia
{
currentSpeed = Mathf.Lerp(currentSpeed, targetSpeed, Time.fixedDeltaTime * 0.2f); // Wolniejsza zmiana prędkości
}
rb.linearVelocity = new Vector2(currentSpeed, rb.linearVelocity.y);
}
}
Can anyone help me.
Okay so there is situation, that player checks ground under him, and ground == 1 is normal, a lot of friction and ground == 2 is slippery, idk 0.7 friction so it's like ice
And i want for my character to slowly gain speed, like in jump king on ice, but i cant do it. Can anyone help me?
I have been trying to change this for a few hours already
Use AddForce instead of directly setting the velocity and that's what you get automatically
it worked, thanks
I have a variant of a menu template that I changed to be a pause menu, but when I press the "pause" button, the menu doesn't pop up and I get a "NullReferenceObject"
{
[Header ("General Values And References")]
public GameObject pauseMenu;
void Start()
{
closeMenu(pauseMenu);
}
void Update()
{
handlePause();
}
private void handlePause(){
if(inputManager.instance.pauseOpen){
if(!pauseManager.instance.isPaused){
setSelectedFirst(pauseManager.instance.transform.GetChild(0).GetChild(0).gameObject);
pauseManager.instance.setPause(true,0,"Menu");
openMenu(pauseMenu);
}
} else if(inputManager.instance.pauseClose){
if(pauseManager.instance.isPaused){
resumeGame();
}
}
}```
{
[Header ("Pause Instance")]
public static pauseManager instance;
public bool isPaused;
void Awake()
{
if(instance==null) instance=this;
}
public void setPause(bool paused, float time, String action){
isPaused=paused;
Time.timeScale=time;
inputManager.player.SwitchCurrentActionMap(action);
}
}```
has anyone experienced a 1px border around Canvas screen space overlay? It seems to be present on all Unity 6 URP setups.
I have the canvas setup to stretch full, ive played with all the settings. Nothing fixes it.
does it also happen with just an empty canvas with nothing in it? also its not a code question, should've asked in #📲┃ui-ux
If i add a canvas with nothing in it how would i be able to identify the issue? Also should I start a new convo in that channel now?
yeah
Anyone willing to help?
You'll have to tell which line throws the error, to start with
I tried creating the menu an instantiated object but it calls an error when I try to close it with the "resume" button in the menu
pauseManage.setPause(false,1,"Player");
closeMenu(pauseMenu);
}```
Do you have an active pause manager object in the same scene?
Yeah
When I press on the escape key, the pause menu pops up which has the manager script, but when I try to close it with the "resume" button on the menu, it causes a null error
Is this now a different problem?
I first want to know why it doesn't work without an instantiate
A static instance is working with my input manager, that is always active
Here however, I can't set the pause menu as active or inactive
Turn on error pause in the console and show a screenshot of the editor window with the pause manager selected when it errors on pause button
@mellow sigil I got a video
That's a different error
because it's a prefab, it doesn't exist in any scenes.
How does a armour system work with a character mesh? like how does armour models get applied how would you model the armour etc
Or a skin system
Hi, is there any simple way to read what key the user last pressed or do I have to go through and manually cover all options the user can press?
is there a way to like script if smth touches you the game kicks u out
Are you using the "new" Input System package with key binding, or the old Input class with GetKey functions?
The old class, the only thing I found with that was the InputString but that only gets ascii chars, since I want to work with the arrow keys that’s not an option
this is #💻┃code-beginner material at best, and have you googled anything about detecting collisions?
if you have specific input you want to check for, then do so in Update and just keep track of what the most recently pressed button was with an enum variable or something
So checking for each possible input manually is best then? I was kind of hoping there was a variable that automatically saves the last key that was pressed
I was kind of hoping there was a variable that automatically saves the last key that was pressed
you'll have to make that yourself which is what i suggested
Oh well… thank you for the help, I shall get coding then
yep i googled and ik about collisions and how to use them , i just cant find smth that kicks u out
btw what i mean by kick not a hit but to make the game close
so now you can google "how to close game" or whatever
i will just cancel this idea cuz u cant rlly do it (you can im stupid)
lemme make escape key close the game
if you'd bother actually researching you'd find it is incredibly simple to do this
i searched and found how to make quit button
wait im stupid
great! so instead of using a button, you quit in the collision detection
it's literally that simple
yepppp
im hella stupid for no reason
or actuacctly im lazy lemme use my brain next time thanks ♥
How do I add a generic extension method?
I'm trying to create a utility method for all my list classes but it doesn't seem to work:
public static class CollectionExtensions
{
public static void PrintList(this List<T> list)
{
}
}
you need a generic type parameter on the method
that would mean I need to define a function for every possible type?
no, that would mean you need a generic type parameter on the method declaration
T does not exist in this context because neither the method nor the class are generic
so like this?
public static void PrintList<T>(this List<T> list)
Sadly, the old input system is fairly "minimal" and doesnt have a lot of features built into it, so with it you would have to create a lot of your own systems, the only thing that system has for "saving the last input" is the ascii you were already using, you could pair that with maybe checking for "modifier keys" (being things like control, alt, shift, etc), that way you dont have to cover EVERY key (or maybe you could convert the KeyCode enum into an array and loop through GetKey calls)
https://paste.mod.gg/zpqydplisqwo/0
Does anyone know how to make the player slowly slide along a wall when colliding with it? For example, in most games, if there's a wall on the left or right side of the player and the player presses W A or W D, they still move forward slowly while sliding along the wall. Right now, my movement system just completely stops the player if they're colliding with anything or if their movement isn't perfectly straight along the wall.
A tool for sharing your source code with the world!
It should pretty much happen automatically
Maybe it's a friction problem?
oh
it turned out
i just needed a physics material on my player
guys what’s a must-have plugin for Unity in VS?
Any recommendations?
VS pretty much has all you need for unity.
If thats the case, then why does my input manager still works?
It is a prefab too
it's also in the scene
Then how is my pause menu prefab isnt in the the scene if I assigned it to be
at this point you need to show your code because it's impossible to guess what is actually happening
Watch this video
i'm not watching a video to see code. if you have !code then share it correctly 👇
📃 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.
@somber nacelle
god so many singletons. what line is the error occurring on
share all of the code because i'm really not about to start playing 20 questions to get all of the context
Actually screw this, Ill just make it an instantiate
I don’t know why I’m getting a not defined error
It keeps telling it it doesn’t exist in current context
We don't have the ability to read your mind or see your monitor/code/error through space and time.
I fixed!
It
I'm making a bullet hell boss and I don't yet have a system for managing attacks. In fact, I don't know how to define an attack yet.
I know what an attack will be: spawning certain prefabs at certain timings.
I know what the attack manager should do:
Attack management system
- Decides what attacks to do.
- Needs to react to various events, such as the player entering an area or boss HP falling below a threshold.
- Needs to be able to track what attack is currently happening.
- Needs to be able to cancel ongoing attacks in response to these events.
- Attacks will need to control various prefabs.
- As reusable and flexible as possible.
Also is there some way to create reusable components you can mix and match to create custom entities?
My best idea is using scripts
So Im working on a generic asset loader for an old game (Im modifying assembly, the game is long dead and Im currently forced to work with the 2018 unity APIs it was built with), and Ive added a bunch of classes to it so far.
Currently everything functions as intended, the asset files are valid, all the paths are correct, and Im sending the right information to the Asset Loader, but when I start the coroutine, nothing happens.
The asset loader is attached.
The last thing I see ingame after running TestConvertFirstSong is a debug output ingame of the fixed path. The path displayed ingame is correct.
The first debug log inside the LoadAudioFile function never even shows up... So I assume Ive built the IEnumerator incorrectly / am using coroutines wrong?
(What I see ingame after running that test function).. Never even logs after the fixed path
unfortunately we can't help with modding as per #📖┃code-of-conduct
Im not asking for help with modding.
This is just a basic piece of code (That I wrote)
What I do with the code isnt really anyones business is it?
it is to mods tbh
Maybe you should ask them instead of assuming?
Im just asking for support with a generic coroutine... I didnt ask for someone to minimod
if you read #📖┃code-of-conduct, you'll see that community members are also expected to help remind people of stuff there
yeah sure whatever
the coroutine looks correct
you probably don't need the yield break; but i don't think it's related to not getting that log
Compiler just automatically places it there unfortunately.
It does that with a lot of stuff actually, I write code but it changes it as it pleases
Luckily its mostly just Efficiency stuff
It doesnt really break anything
i mean it is kinda implicit at the end of the enumerator anyways
Assuming you have access to the player log, you should check it. I feel lik you have a null reference there
maybe try a different yieldinstruction to test, just yield return null; or yield return new WaitForSeconds(1);
To confirm that print something right after the yield
Most of the time it should log exceptions to my custom debug console, but that one may be out of the context of the catcher
Unless coroutines just inherently dont get caught in the same way
No idea
it may be an issue with the usage of WWW
Notes http://, https:// and file:// protocols are supported on iPhone. ftp:// protocol support is limited to anonymous downloads only. Other protocols are not supported.
Note: When using file protocol on Windows and Windows Store Apps for accessing local files, you have to specify file:/// (with three slashes).
other platforms aren't mentioned
Anyways, logging right after the yield should provide some clues
Tried this and it still didnt log
uh the log before the yield isn't getting logged
So either it cant log in the context of the coroutine, or the coroutine just isnt activating for some reason
¯_(ツ)_/¯
It is in the screenshot🤔
it isn't; that's the log before calling the coroutine
they're slightly different
Aah, I see. That's confusing
Yeahhh
This log works great
The one that logs the same path in the start of the coroutine isnt logging
This might actually be a modding thing.
Now, it could be an issue with my shoddy logging system, Ive had weirder issues
But theres no other way to get realtime debugging afaik

This should work perfectly fine in a normal project
If you have debug symbols, you could attach the debugger.
That a DnSpy feature or something? Im unfamiliar
Which you should, seeing that you're modifying code and supposedly compile it
No. Simple ide debugger.
It's not modding/decompiling related.
Oh then Im unaware of how to do it. In theory though the logs should have everything sent ingame
its just a pain to work with
closing and opening the game, constantly reloading the text files lol
Learn how to use the visual studio debugger.
This is making a lot of assumptions on the game that you're modding and the modding workflow though, so you should probably move to the game modding community.
Got an invite? Ive been out of the unity scene for years
Im mostly just doing this for a friend whos maintaining this old game / building a private server for it
No. I don't even know what game it is.
There's no such community. Or I don't know about it.
Every game modding workflow would be unique and different depending on what the game allows.
Well I guess there could be other ways to prove the coroutine is running, if my logger might be the cause of my confusion...
Is there a way to tell when the coroutine is finished outside of the context of the IEnumerator
My guess is that you're injecting the code or something. That might fail on many levels with more advanced features like coroutines.
Oh Im directly modifying the assembly
All of my code runs in the same context as the original
It should behave as normal / have access to all the same libraries and systems, .NET or otherwise
That's not the point. The point is that it's probably bypassing the normal unity compilation pipeline, possbily missing some steps, like codegen and such that could be required for coroutines to work(all assumptions).
Possibly, I had that concern too, but when I looked at the compiled code for other MonoBehaviors / coroutines, it matched mine
All it does outside of the editor is convert StartCoroutines to base.StartCoroutine and it adds yield break; at the end of functions that didnt declare it literally
Atleast as far as I can tell
The rest of it matches the unity API standard
Im assuming that, since theres no errors, theres a likely chance that the coroutines ARE working
Im just unable to log from the context of inside the IEnumerator
¯_(ツ)_/¯
In which case debugging will be slightly more annoying, but not impossible
Okay yeah Im stupid lol... I just attached a try catch to the start coroutine...
Definitely a null reference there
Now what that means? No idea
I guess the most obvious option is that it cant see the loadaudiofile function
though that doesnt really make sense
DnSpy seems to detect it as a safe reference
This seems to be mostly about modding. Please use a different server for modding activities.
there is not much to think about with coroutines, its like are you yielding correctly and is the coroutine running on a enabled object
That might be the issue then... I just defined the monobehavior like a normal class
Does it require I create an empty to attach it to ingame?
yes it requires a fully working MB to run on
thats probably the issue then.
that is on a game object that is active
also what do you mean defined like a normal class?
MB's should never be created with new
if you need to add one at runtime use AddComponent<T>()
I mean I just created a new class, tossed it in the game's assembly, and defined it as a MonoBehavior.
Works fine for everything else ive done
but Ive never tried it with monobehaviors
So this is a bit of a first for me frankly
this is pretty basic unity 101 stuff
To be fair, I made like one game with unity some 6 years ago 💀
I havent touched it since hah
but MonoBehaviors only properly work if they have a instance on a GameObject
Gotcha... Should just be fine if I add the script to an empty and instantiate it during runtime?
Or can they not be handled like that during runtime
otherwise they do not receive any of the messages from unity like Update
(I know this is sorta nonstandard but Im working with what ive got lol)
they can be added to GO's just fine at edit time or runtime
Alrighty, Ill give that a try
though like proper workflow you know is to just add them in the editor
you're trying to fix a coroutine that appears to be broken for reasons outside of unity, considering the modding aspect. this is what i tried to warn you about 
but yeah 100% sounds like they are trying to mod a game without understanding unity enough to do so
Ik... btw since I have a global reference / instance to this script, would it be fine if I just initialize it with the monobehaviors start function?.. just to make sure I dont create the instance before then?
and using that is a entry to unity is going to be a rough time concept wise
Eh, not the worst thing Ive ever had to learn.
Ive always been self-taught when it comes to code lol
It has its problems, but I work with it
i am not commenting about self learning code like most people do that
Well, I just found out theres probably a very normal and obvious reason its broken thats absolutely not "for reasons outside of unity"
So Im not sure what youre talking about lol
the fact that it's not on a gameobject? that's absolutely outside the normal bounds of unity.
Bruh... what... what kind of mental gymnastics is that
"monobehaviour not a gameobject" is not a normal unity situation/issue
its absolutely within the context of unity and something Im sure people can easily mistake
it isn't
:/
so... that's kinda speaking to your inexperience with unity?
Sounds to me like youre just trying to justify not giving someone support for no reason other then feeling self-righteous..
components just don't exist outside of gameobjects in the proper context of unity
hey, not like i didn't want to help. but it's just not a topic this server wants
your issue arose specifically from modding; modding-focused communities would be much more well-suited to help you
modding is not on topic for the server
ive had literally no issues so far that arent basic unity-specific mistakes / programming mistakes? Ive run into nothing thats specific to "modding"
Like if I didnt even mention it to you guys you wouldnt even be fussing
and the relationship of components to gameobjects is literally impossible information to avoid
Someone doesnt attach a script to a gameobject:
which just isn't something that happens in unity lmao
We don't provide support for modders regardless
you don't manually attach scripts to gameobjects as a separate step
you create scripts directly on gameobjects
that's just how unity works
Youre genuinely one of the most toxic people Ive been forced to interact with on here... Why are you so obsessed with trying to invalidate a discussion.
Because it's against the rules. Let's stop this here.
Cant imagine how you guys treat people new to unity if this is the norm
i tried to warn you 
you asked for a mod opinion and got a mod opinion, what else do you want lol
@vestal arch no need to comment more and prolong this, its handled
Well, this solved it, thanks... Even if everyone had a fit about it
It took a sec to realize I couldnt instantiate directly since the startup code isnt even run from a monobehavior, but I got it working
i would not call it a fit, its a rule since without it everyone just tries to get help with VRChat and other stuff and it drives things wildly off topic
also that is till incorrect and you are making more gameobjects then needed
We treat them just fine. As long as they follow the community rules. If you don't like these rules, you are free to make your own community🤷♂️
Oh, then Idk, but for all intents and purposes this works for what I need.
It only runs once on startup just to load some files and stuff and convert them to specific asset types like audioclips and whatnot
(editing assets is a hellhole Im not climbing down)
Im usually fine in my community 99% of the time... I mean we built an entire private server for a dead game and got it running... So we usually do pretty fine on our own
I just had a basic error because, unfortunately, Ive never really worked with unity in a serious manner
atleast not in many years
so Ive forgotten a lot of the basics
use it or lose it, as they say
Just saying, if you're going somewhere, adhere to their rules. That's true to everything in life.
Any downside is writing my custon .lang file type for handling localization instead of using json? i think that a custom file type would be easier to write, like
cards.cardEffects.basicDamage=Deal 2 damage
instead of messing with brackets etc...
you may find yourself wishing your strings were encased better as you have more multiline strings and dynamic content? also creating your own format means you can't use any existing json editing/validation tools
you could always use some other existing format, like yaml or ini or toml
Depends a lot on your workflow. If you are going to translate by actually modifying the file by hand, then sure. But if you want to integrate the workflow into some translation platforms, then you should not worry about what the file looks like and instead look at what's supported.
feel like i would just use a established format that way i do not waste time on sorting out how to parse multiline strings or escaping stuff
json you likly already got deserilaizer for, and TOML is a good choice for a easier to human edit thing
Anyone know what formats WWW accepts for audio files? It has a GetAudioClip() function but it seems to always throw a null reference exception when I use it, whether its .wav / .m4a / .mp3.
Ive verified www works, the bytesDownloaded reads ~14mb, which is the size of the audio file
show your code and the full error message
Also you should be using UnityWebRequestMultimedia generally
WWW is deprecated
Cant use unity web request since Im stuck on unity 2018
im not seeing the function you mentioned in docs
I was missing the exact AudioType optional parameter I just noticed
so ill try setting that
It may just be failing to read the extension or something
The data must be an audio clip in Ogg(Standalones), MP3(phones) or WAV.
Says right there in the doc
huh that was removed in the 2018.3 docs, i guess because it's marked obsolete
Yup. Converted between wav and mp3, defined it with AudioType
Well, Im in unity 2018, gotta work with what I got
then back to #archived-code-general message
yeah im aware
i mean - the docs for 2018.1 and 2018.2 list the method in the docs, but not 2018.3 or 2018.4
Error: System.NullReferenceException: Object reference not set to an instance of an object at ExternalAssetLoader<LoadAudioFile>
public IEnumerator LoadAudioFile(FileInfo file)
{
string url = string.Format("file:///{0}", file.FullName.ToString());
TheGreatDebugMenu.QuickLog("Loading File", url);
WWW www = new WWW(url);
yield return www;
try
{
TheGreatDebugMenu.QuickLog("Loaded Data", www.bytesDownloaded.ToString());
this.clips.Add(www.GetAudioClip(false, false, AudioType.WAV)); // Problematic Line
yield break;
}
catch (Exception err)
{
TheGreatDebugMenu.QuickLog("Asset Loading Failed!", err.ToString());
yield break;
}
yield break;
}
It doesnt say what line for some reason but its being caused by the one I commented on
unity 2018?? fuck thats old
Probably this.clips is null
what an awful emoji
anyone tried latest unity/ .47f1, somehow rigid bodies are VERY slow here, bring my game to less than 1fps
guys how do I work with tilesets in unity? All I found seems rather outdated, there has got to be a proper workflow
I dont want to create yet another custom tool just to automatically create tile rules...
Checkout Tilemap tutorials on Unity !Learn and pinned materials in #🖼️┃2d-tools . This is a code channel.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Is it possible to connect the Skylanders portal to Unity and read and write innit ?
From what I remember, it's literally just an NFC reader
Bring back skylanders!! 🔥🔥
But I don't know if you can do anything like activate the lights and whatnot on it without reverse-engineering some sort of driver
But you can probably get your computer to recognize it as an NFC reader with enough shenanigannery
i wouldnt be suprised if something already exists and if it has exported c functions then you can use it
Yeah, modders are pretty good about making those old quirky hardware experiments survive well past end of life
The Xbox 360 Kinect is still the best consumer-grade 3D-motion tracking device ever released
anyone knows how to make a serialized dict work? everytime i try to add a value or key i get ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
You need a class for it
Lemme find mine
public abstract class UnitySerializedDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver {
[SerializeField] private List<KeyValueData> keyValueData = new();
public void OnBeforeSerialize() {
keyValueData.Clear();
foreach (var kvp in this) {
keyValueData.Add(
new KeyValueData() {
key = kvp.Key,
value = kvp.Value
});
}
}
public void OnAfterDeserialize() {
Clear();
foreach (var item in keyValueData) {
this[item.key] = item.value;
}
}
[Serializable]
private struct KeyValueData {
public TKey key;
public TValue value;
}
}
Then define a dictionary using something like this
[Serializable] public class TypeObjectDictionary : UnitySerializedDictionary<Type, object> {}```
then use that type as your dictionary
So the one unity has ain working?
Unity doesn't have a serializable dictionary afaik
It unfortunately does not, Packages like odinInspector do, otherwise you can serialize it yourself with a custom editor
This dictionary is Odin inspectable btw, looks really nice with Odin installed
Dunno if thats the one i used cause im not on pc rn. It shows two lists in the inspector but cant add stuff in them
Didn't know about that one. Show us the code you used to cause the error when you get to your PC
Actually this isn't Unity's, just looks like it made its way into the docs
Unity can't serialize Dictionary so here's a custom wrapper that does. Note that you have to extend it before it can be serialized as Unity won't serialized generic-based types either.
Hey, I am trying to do a DevLog, BUT when I when I switch to a version before the newest they will overlap. For example when I switch to a scene where the obj didn't exist before they exist there now but there Prefab is not in the Project folder. All the Project files are chainging but the scene is not. Why?
Sounds like you're modifying prefab files instead of instantiating and modifying them to me
So somehow I switched to a changeset just fine but when I went back all my scene Obj were different Before:
After:
You sure those are even the same scene?
also that "before" has an unsaved samplescene 
yeah 100% same scene but In the second photo I switched to an older changeset and back
Because I moved an obj, and It is the newest version
I found out that the obj in the scene is only changing when I switch to a specific changeset
i just declared a public var public SerializedDictionary<string, GameObject> _prefabs;
Interesting
extending didnt work
Show the code causing the error
weird question. not so much code related but Unity. When i start my game my computer literally starts screeching and making weird noises LMFAO. NO idea why and it only happens when i open my project, no other game. no one would happen to know why, would they? I don't even know where to begin to know what is causing it or if its even an issue lol
Probably GPU coil whine
try limiting your framerate by turning on vSync or setting a max framerate
e.g. Application.targetFrameRate = 60;
what even is this, is it just when the speeds are too fasts?
Been using this for a while, it’s very helpful
Eh... just look it up, the internet can explain better than I can
okay bet, sounds good
how did u make it work?
general physics question, how could I factor linear damping into applying a force to ignore the damping in that specific direction, a bit lazy to deal with adding my own counter forces so wanted to try utilizing linearDamping
@leaden ice yeah, that was definitely the issue using vsync and limiting the frames fixed it. It also fixed the issue where my VFX / particles were moving at lightning speed in the build while in the editor they looked fine. Maybe i just keep players framerates capped 🤷♂️
I am using rb.addForce for my movement if that helps
Use the angle or dot product between your velocity and that specific direction. Then modify linearDamping based on that value.
send a picture of your code where you declare the variable
hold on- I actually use a 3rd party one by AYellowPaper
works out of the box just fine
example usage
thanks will try it and tell u
That latter part would have to do with your code being framerate dependent.
Which you need to fix separately
how is it supposed to be installed?
meh u gotta put the whole thing in his namespace
you shouldn't have to, you can add the namespace at the top, using SomeNamepace;
tried didnt recognize it
@wicked mountain did u have to declare the dicts in his namespace?
I didnt have the edit the code at all
I just used it like this:
[SerializedDictionary("Name", "Stat")] public SerializedDictionary<string, Stat> stats = new();
Do you use assembly definitions?
your IDE probably automatically imported the namespace. Check at the top in the usings section.
You installed it from the asset store?
most likely
yup
I must be missing something about how packages work in Unity 6. I have included a newtonsoft json package by adding it manually.
But I can't seem to call Newtonsoft other than as a Unity.Plastic package??
are you using assembly references?
No, this is a package I added with com.unity.nuget.newtonsoft-json in Unity
Using this option
Yes but is your code under your own Assembly Definition? Or does VS say your assembly is Assembly-CSharp?
The latter.
turretList = new List<GameObject>();
enemyList = new List<GameObject>();
projectile1List = new List<GameObject>();
projectile2List = new List<GameObject>();
projectile3List = new List<GameObject>();
projectile4List = new List<GameObject>();
barrier1List = new List<GameObject>();
barrier2List = new List<GameObject>();
barrier3List = new List<GameObject>();
}``` need someone smart to give me some advice on how to create a ton of specific objects for each one of these lists, trying out object pooling
i could use a for loop for all of them and add onto them but i feel like there's an easier way
or well, simpler
If it's not, then try regenerating the project via Preferences/External Tools in Unity, and restart VS
Alright
And make sure you have no compiler errors
Yeah I'm suspecting perhaps compiler errors made the package simply not compile or something
I'll try those things
Okay took a few tries. Had to remove the package from Unity, re-add it and then regenerate @quartz folio
Thanks
No
Tried adding the import by hand but nothing lemme try again
why are they all GameObjects and not Turret, Projectile, Enemy, etc?
because some of them have Deployable script, some have Projectile, I dont have a specific script for each one, therefore their type is GameObject
But, like, surely everything in turretList is going to have some script in common, right?
You should make the list of that type
whats the difference between using a list of a script reference, vs the GameObject?
seems like the same thing
A GameObject gives you access to like, the name and tags and that's it
A reference to the component you actually want lets you access all of the things in that script
Oh, well I just need a reference to the GameObject, because this is for Object Pooling, disabling and enaaabling the object
thats all
And you can always get the GameObject a script is attached to with .gameObject, but getting a component requires GetComponent which is slow
Thats a good performance tip, thankyou
I guess Ill just write a for loop for the lists lolo
turretList = new List<GameObject>();
enemyList = new List<GameObject>();
projectile1List = new List<GameObject>();
projectile2List = new List<GameObject>();
projectile3List = new List<GameObject>();
projectile4List = new List<GameObject>();
barrier1List = new List<GameObject>();
barrier2List = new List<GameObject>();
barrier3List = new List<GameObject>();
// Initalize all objects into lists
// turrets
for (int i=0;i<turretListSize;i++){
GameObject newObject = Instantiate(turret);
newObject.SetActive(false);
turretList.Add(newObject);
}
// enemies
for (int i=0;i<enemyListSize;i++){
GameObject newObject = Instantiate(enemy);
newObject.SetActive(false);
enemyList.Add(newObject);
}
}``` ended up just doing for loops lol, like this
you should really just rewrite this all, especially so you dont have list1 2 3 4 for everything you do. this is going to be awful for you in the future.
Even if you were to continue like this, surely with all the repeated code you couldve just made a method
void PopulateList(List<GameObject> listToFill, GameObject prefab, int count)
...
man why didnt i think of that *facepalm
if you're not too familiar with c# or coding then maybe post future questions in #💻┃code-beginner
even with this change the code here is very tedious to work with. unitys netcode has an example for an object pool manager, but uses a network related component in it. If you want to follow it, you just need to change that type to whatever type you want https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/object-pooling/
Im not new to programming, just didnt think to turn that into a method, somewhat new ish to c#
How can I make googly eyes? I tried using edge colliders and rigid bodies but that didn't work. The googly eyes push against the player and they can also clip through the eyes themself
I am making the googly eyes move in the opposite direction of the player
That's something out of nightmares.
On the topic though, you have several problems that you need to solve:
- both(?) the eyes and the body needing to be controlled by physics means that they would collide and affect each other. Maybe you can consider hardcoding the eyes behavior instead of letting physics control them.
- since the eyes are controlled by physics, they collide with the character collider, causing an outwards force. Perhaps you could place them on separate layers that don't interact?
Overall, I'd consider not using physics for the eyes.
oh lol i didnt know that
yeah it'll make the bullets go much slower
idk why it does that lemme try removing that and check again
uhh it doesnt work still
idk why it stays up like that
you make it look up
wait what
Vector3.up = (0, 1, 0) iirc
💀
im stupid
u are right the position is fixed
but idk why it doesnt fire
like it stays
does anyone know how to stop the Player camera from clipping and seeing through walls "im in first person"
I told you that in the main chat lol
Don’t crosspost but did you try lowering the clipping for your camera?
Can someone help me out here? I'm messing with online right now using netcode for entities (this guide: https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/build-with-netcode-for-entities), but the player prefab does not work correctly. The one in the air with no gravity is the online player, and the one on the bottom is the offline character, how it should work. I'm not really sure how the online works, so i'm having a hard time figuring out what the problem is. Any help is appreciated!
#archived-networking has pins to Netcode w/Entities channel discord
Oh perfect, thanks!
Hey guys, I'm trying to write a script that hides the back of the walls when they are facing my camera, so I can have a full view of the room every time.
I'm not sure what is wrong, because sometimes I still can see the back of the walls. Any idea on how to do it?
This is my curent iteration of the code:
using UnityEngine;
public class WallAutoToggle : MonoBehaviour
{
public float threshold = -0.5f; // Hide when the camera is looking at the wall's back
public Transform cameraTransform;
private bool isHidden = false;
private Renderer[] renderers;
void Start()
{
if (cameraTransform == null)
{
if (Camera.main != null)
cameraTransform = Camera.main.transform;
else
{
Debug.LogWarning("WallAutoToggle: No Main Camera found! Assign cameraTransform manually.");
enabled = false;
return;
}
}
renderers = GetComponentsInChildren<Renderer>();
}
void Update()
{
if (cameraTransform == null) return;
// Direction from wall to camera
Vector3 toCamera = (cameraTransform.position - transform.position).normalized;
// Compare wall forward to direction to camera
float dot = Vector3.Dot(transform.forward, toCamera);
bool shouldHide = dot < threshold;
if (shouldHide && !isHidden)
{
SetRenderersVisible(false);
isHidden = true;
}
else if (!shouldHide && isHidden)
{
SetRenderersVisible(true);
isHidden = false;
}
}
void SetRenderersVisible(bool visible)
{
foreach (var rend in renderers)
{
if (rend != null)
rend.enabled = visible;
}
}
}
Gonna be honest, I’m not sure why you pinged me, but can you do a one sided wall instead? If the mesh only renders from one side, that would work right?
Since you answered anyways....
These walls they have depth, soI don't think I can do that
Ideally I want somehthing like, "if any point of the back of the wall is visible, hide it"
#1 raycast to the wall from equal the wall's position.
#2 check if its the back of the wall by its forward vector, this can by done by the Dot product (this also mean every wall needs its forward vector facing inwards)
#3 hide the object
Code design question
I have inventory in my game. I want to have items in it with whatever associated functionality.
I also want my code to be modular: modules not being dependant on anything not strictly related to it.
There are these classes already:
Module 1: Inventory InventorySlot InventoryItem
Module 2: InventroyUI InventorySlotUI InventoryItemUI -> dependant on the above by design.
Module 3: PlayerInventoryController -> dependant on Inventory by design (takes input and selects InventorySlot)
But lets say i want some items that have some special effect displayed every frame they are selected.
I would create something like PreviewItem class. But how do i structure my code to include/use it?
I dont want to just include a reference to it to InventoryItem because it doesn't relate to inventory module. What if in the next game i dont want any preview? I would have to crop the code. If i leave the field empty it still feels wrong: imagine i had 50 distinct item functionalities. If i include everything as InventoryItem field it becomes unclear which ones actually need to be filled for inventory system to function.
You can use an interface to add functionality without adding useless references.
You can have a 'IInventoryPreview' interface that has an Effect() method.
You can reference the interface in InventoryItem or any classes as references. There you can define their functionality related to the item.
InventoryItem takes in an object of Preview. When the item is selected or used, check if there is a Preview object and execute what logic it contains, otherwise ignore
Example1:
{
Public void Effect() { // spin or something }
// every item does this now
}```
Now you can access Effect by getting the interface as a component.
Example2:
``` public class Fruit: Item, IinvPreview // inheritance from a generic item class
{
Public void effect() { // explode }
// now every fruit type will explode when called
}```
If the InventoryItem has a reference to a generic item class you can getcomponent<IinvPreview> to all the Effect method
Thanks for the answer but it's not what i'm looking for. I don't want all the inventoryItems to implement Preview interface
Uhh make an scriptable object with the method and other stuff you want the item to do and have a list with those scriptable objects in InventoryItem.
Could be a solution
It could be but still would mean i have to have a reference that is not related to inventory module
is it possible to export the texture from a material, if the texture isnt readable?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Material-mainTexture.html
you can get and set texture from a material
Yeah, but i need to Export it, as in to a file
Because a fonts Materials MainTexture is black, and i wanted to make it White.
theres an imageconversion module
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Texture2D.html
"The ImageConversion class provides extension methods to this class that handle image encoding functionality. For details on those methods, see the ImageConversion documentation."
this should help you out
Thanks!
you can use Translate instead, something like
void Update()
{
transform.Translate(Vector3.forward * bulletSpeed * Time.deltaTime);
Destroy(gameObject, 3f);
}
Controls? What are you asking?
Im trying to make my enemy to take a longer path instead of taking the way that goes over a wall. Here I explain it better https://discussions.unity.com/t/a-pathfinding-2d-set-tag-problem/1633308
- you're calling a
Destroyevery frame lol - they have a rigidbody, which this would conflict with
<i>Autoconnected Player "Autoconnected Player"</i> StackOverflowException: The requested operation caused a stack overflow.
I'm trying to run a test but I can't as the player instantly gets shutdown after building due to a stack overflow exception, I cannot find anywhere any log about what might be causing this
do you have stack traces turned on in the logging settings? i think that error should normally come with a stack trace
There's too many logging options, do you mean Preferences > Scriptable Build Pipeline > Use Detailed Build Log?
the one in player settings, you can also change it in the menu on the console view in editor:
Share the whole error details. Take a screenshot.
Hold on, I'm trying to rerun it and I'm no longer getting the stack overflow message but the player is still getting disconnected
I'm just not getting anything now, the disconnect message says nothing and the test runner is permanently hung on "wait for player run"
What platform are you building and connecting to?
That might be complicated then... I don't think there are many devs here that worked with unity on Linux. Definitely not me.
Absolutely did not happen yesterday at the very least so I'm extremely confused, I just changed the code in my test
Solved, I was looking how to get a Tile color. I dismissed Tilemap.GetColor as I was expecting it to return the color of the Tilemap. Turns out it takes a Vector3Int in and output the color of the Tile at that position
Thanks! Will give it a try later today
youre right, meant on Start()
I have this bit of code inside Update() Is it really allocating 3 Vector2s every update, even if it's the same values every time? Or does it get optimised away by the compiler? Do I need to painstakingly check every single value, to determine if it needs updating?
Please ignore the variable name, I'll change it, I wasn't the one to decide on it though
I can't put it in OnValidate before that suggestion appears
Vector2 is a struct, a value type; it's not allocating anything on the heap
the values do get created every time, though it's basically just 2 floats each
oh then it should probably get optimised away by the compiler anyway, not that it matters if it's not allocating
but damn, I could've sworn vector2 and vector3 were classes! Why does float2 and float3 exist then?
that fits into a word on a 64-bit processor, so maybe that's optimized as a single instruction each, but i don't really know how structs work internally so im not confident
in the Unity.Math library
probably implemented differently for ease of use vs performance?
unity.mathematics*
perhaps
why did I have it in my head that vector3 is a class, though... huh
Unity Mathematics is a C# math library that provides vector types and math functions that have a shader-like syntax, similar to SIMD or HLSL. The Burst compiler uses Unity Mathematics to compile C#/IL code into highly efficient native code.
there is no way it has to be in Update() tho. What about Start()?
sadly, it does have to be in update, becauase those values could get changed by something at runtime, and this script strictly relies on those values remaining as they are - although if it was an allocation, I'd probably rework it to not do that
does that not dirty the canvas per frame?
Hi
I want to deactivate my player input at a moment (I have several and want to deactivate it at the same time)
I tried Deactivate PlayerInput, doesn't work
I tried actions.Disable(), doesn't work
I have this config on my player prefab (default input system actions)
I highly doubt these structs will heap allocate so I wouldn't worry about it
If a new struct was passed as an arg Id expect it to be stack allocated too
I know mono is kinda shit but its probably not that shit
Try looking for the InputUser and getting the input map he has assigned
My problem was my object with this script is on DDonLoad so it always in -1, never change scene
Doesn't PlayerInput hold a reference to the user it creates?
You can save the value as a static variable at the top of the class right?
wouldn't even need to be static, I guess - but since it's not an allocation, doesn't matter
Idk if this is the right spot to ask but:
Can someone pls help me. I feel like I'm going crazy
I am trying to mod Schedule 1, and load in an asset bundle. I cannot for the life of me get it to load in.
I am using UnityEngine.dll, UnityEngine.AssetBundles.dll, UnityEngine.CoreModules.dll from unity hub folder version matching the one Scheule 1 was built on. I would appreciate any help
modding discussions are not permitted in this server
you can typically find help in the game's modding community if you need help with mod related stuff
where can i find that? I'm sorry
Anyone is an expert on A* pathfinding 2D?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
i am guessing he is referring to this: #archived-code-general message
Is that the aron granberg's package or what?
Because "A* pathfinding" doesn't sound very specific
It's a very common algorithm used in pathfinding
Hiya! I could really use some help with my raycasting code, I'm trying to make a laser-reflections game that involves the player shooting out light in the direction of the mouse, and reflecting it off of mirrors.
For some reason, the reflections work great on one side of the mirror, but not on the other. Does anyone know why this might be happening?
You'd need to show your code of course
Yes, this one
I am using a* to detect the layer 'ground'. I want part of this 'ground' detected not to be walkable by the enemy, for example a wall or something like this. I added tag to A* as 'Wall' and then on the seeker y set the tag 'Wall' as not travesable. Then I set to the wall the layer 'Ground', a Box Collider 2D and the script GraphUpdateScene, with the only the Update Erosion not checked and the Walkability Value not checked. Modify Tag is checked and Tag Value is as Wall. But it does't work
Is like it doesn't change the wall tag
You should ask in the discord server of that package.
Also, don't DM people randomly
Right! Sorry about that 😅
Try posting your !code with one of the sites listed from the bot . . .
📃 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.
Everyone will have a better chance to look at it . . .
That, but yeah this doesn't make sense:cs Vector2.Reflect(mirrorHitPoint, mirrorHitNormal)
Reflect is meant to be used with two direction vectors but you are giving it a position and a direction
Should probably replace mirrorHitPoint here with the direction of the first raycast
Ohhh that makes WAY more sense now, I changed it from
Vector2.Reflect(mirrorHitPoint, mirrorHitNormal)
to
Vector2.Reflect(playerMovement.aimDirection, mirrorHitNormal)
And now it's working great! Thanks for the help :]
I have an enemy with multiple colliders, one for detecting the player at a distance to chase, another to detect weapons that are attack, which I was leaving to the collider inside the CharacterController. My issue is how do I discriminate between which collider has been triggered? in
OnTriggerEnter(Collider other) other refers to the weapon that has triggered am I correct?
because right now any collider on my enemy with the isTrigger == true, inducing the chase collider is giving false positives for damage. So how would I mask out any other colliders on the enemy.
put scripts on different children colliders/gameobjects, or forget colliders and start using proper physic queries which allow you to specify what hits what from whoo
