#archived-code-general
1 messages · Page 119 of 1
This is how I define the time
TimeOfDay += Time.deltaTime * timeSpeed;
TimeOfDay %= 24;
ah yea then just store the int as suggested
if you want precision dont += delta time
What should I do instead?
give me a sec i had an example of proper accumulation
yeah seems i got time accumulation from time system confused with time accumulatior errors from ticker
with a ticker you cant just += delta you have to compensate for tick overshoot
with just a time system its fine, according to my old code
All right.
You just need to -= the duration instead of setting to zero when you tick over
A mod works just as well since it preserves the remainder
ty
yes i vaguely remember all that but it was long ago so its foggy
Lost in time like tears in rain?
I need to organize my snippets better, I keep having to redo stuff bc I forget where I solved it the first time
and i dont have to copy, i already have Ticker class in utils lol
float time = GetTime();
if (lastTick + Tickrate < time)
{
DeltaTime = time - lastTick;
lastTick = time;
++TotalTicks;
return true;
}
this isnt correct ticker tho
If you want to detect whether a new hour has passed regardless of tick rate, check for the delta change rather than the real number
In other words, save the previous tick and compare the hour of that tick to the hour of the current tick, and emit an event if they're different.
If you want to be sure you will never miss an event (eg. If you think it is possible to skip an hour between ticks for some reason), you can loop over the difference between the two, adding 1 hour each time, until you catch up to the present
In most cases that loop will only execute once ofc
This becomes useful if you have a hyperspeed fast-forward feature for example
It's also the basis for how the fixedupdate loop works
I see, that's very useful, thanks.
found it
protected override void Tick(float dt)
{
// Get Scaled Time Passed
double scaled = Time.deltaTime;
totalTimePassed += scaled;
ulong ticksPassed = (ulong)(totalTimePassed / SR.DT_NORMAL);
if (ticksPassed != lastTicksPassed)
{
int ticksToAdvance = (int)(ticksPassed - lastTicksPassed);
for (int i = 0; i < ticksToAdvance; i++)
{
tick++;
foreach (var tmono in registered)
{
ulong lastTick = tmono.LastTick;
TickRate tickRate = tmono.TickRate;
if (tickRate == TickRate.EveryFrame)
{
if(tmono!=null) tmono.Tick_Int(Time.deltaTime, tick);
continue;
}
ulong tmonoTicksToAdvance = (ulong) SR.GetTicksToAdvance(tickRate);
if (tick - lastTick >= tmonoTicksToAdvance)
{
tmono.Tick_Int(SR.DT_NORMAL * tmonoTicksToAdvance, tick);
}
}
}
lastTicksPassed = ticksPassed;
}
}
jesus, good thing nobody ever seen this
Not anymore
I'm trying to make a small, catapult-style flight arcade game and I'm struggling to figure out flight. After being flung, the player will fly similar to how a paper airplane might - being able to angle up to gain some altitude but sacrificing speed, and vice versa. I'm struggling to figure out the best way to approach this. Using physics would make my life a whole lot easier, but would then require having the player actually move, which seems insane for a flight game.
Does anyone have any experience with this? 😄
"having the player actually move" seems like a prerequisite for a flight game...
If you'd like to use physics, you can jump all objects towards the origin whenever you get a certain distance away from it
yeah physics work in the parents frame of reference
I hadn't thought about that 😓
what was the initial concern?
why does it seem insane
Floating point precision id assume
the assumption is clear
maybe its something trivial, like camera
"having the player actually move" is weird sentence
As opposed to keeping the player fixed and moving the background
Seems like the game idea very much revolves around physics too
Like flappy bird
Pretty much what Mad said
I think it'd be conceptually simpler to move the player in this case
Yeah, you're right - thanks!
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
As for the plane physics, break down the forces involved. As the nose tips up or down, increase the force of gravity proportionally.
When moving upwards, gravity will cancel out the forwards momentum. When moving downwards, it will compound onto the forwards momentum
no code worth showing yet, just wanted input on the 2 different approaches and any major pitfalls
When moving flat, gravity can be basically 0, or some minimum value
no thats my bad sorry, just wanted to know how to post XD
ahhhhhh, this is what I was missing. I'm embarrassingly bad when it comes to general physics/maths.
I knew that a player nosediving and then leveling out should affect forward momentum, but didn't really know how to calculate it
Then just make sure your plane is pointing in the direction of the velocity and it should make a decently convincing effect
Khan academy is pretty good
could you explain this to me? I had the idea that the plane would be pointing whichever way the user wanted to, and the calculations would happen as a result of that, rather than vice versa
https://paste.ofcode.org/MaMcC8bY2mUtXnjTUW9XzB I don't know what is wrong, I thing that clickedGameObject is set before that vector 3 is created
I'm speaking graphically. The player is affecting the direction of the velocity vector
If the player tips the plane up and it starts losing speed, you want the plane nose to naturally tip downwards as it loses enough speed
That will happen if you track the plane onto the velocity vector
Is there a way to call Input method for mouse wheel without using string?
Is this an academic question or is there a reason you can't use a string?
yeah, i want to use in burst
Input.mouseScrollDelta
Y
thanks
im trying to instantiate a game object with a specific rotation but am cant seem to get the object to face the right direction. I think the issue might be with my use of quaternions but I'm very confused by them. any suggestions
Can you describe the specific direction you're trying to achieve
i have two versions of the functions, one where I manually set the direction with a vector and the other that is based on mouse position
this is for a 2D game
so I just want to change the z axis
this is what ive been trying to use https://gdl.space/raw/oguyakahik
What is it currently doing wrong
the objects dot spawn with the correct rotation at all.
Ive tried setting the eular manually to 0, 0, 1 and i get a rotation of -57
probably the issue with Camera.main.ScreenToWorldPoint(Input.mousePosition)
you need to set the z in Input.mousePosition
is it 2d?
yeah
var mp = Input.mousePosition;
mp.z = 0;
Camera.main.ScreenToWorldPoint(mp);
assuming your gameplay is happening at 0 z
ive tried setting spawnedAttack.transform.rotation = quaternion.Euler(0, 0, angle); to be spawnedAttack.transform.rotation = quaternion.Euler(0, 0, 1); so that im not using the mouse position atall and it still gave me the wrong z rot
yeah it is, ill try that now
thats not it probably now looking at the rest of the code
ScreenToWorldPoint returns a value
hahaha thank you for trying anyways
to clarify - the z should be the distance from camera near frustum plane to the actual world point you want to sample
in case of 3d perspective camera
i dont know how it behaves with ortho
I work with all my objects set to 0 on the z axis
so when you do
Vector3 lookDir = mousePos - spawnTarget.transform.position;
you are getting a direction vector that points somewhere off the plane where game is happening
if the camera is at z 5, its gonna point towards the camera
assuming in 2d it uses near camera plane
Ortho works the same for the record
then yes you have to set mousePosition.z to camera.position.z * -1
null reference means "Unity checked this object, but it wasn't there"
It could be because a clickedGameObject that you clicked earlier has been deleted afterwards
Is your object a child of anything
nope
actually it shouldnt matter you can just z = 0 the result vector as well
basically flatten both vectors on z before doing anything with them
Can you show a screenshot of the transform when you use 0,0,1
I dont think the issue is with reading the mouse postiton as even when I spawn an object with a preset direction vector it still spawns with the wrong rotation
sure
What happens if you remove the rotation code entirely
@swift falcon
if all you need from the clickedGameObject is its rigidbody, you could use
RigidBody clickedRigidBody = hit.rigidbody;
instead of the getting the gameObject, but only using the rigidbody of the gameObject.
I'm going to look a bit into your script and see what's up with it
they move straight to the right
rotation of 0
Can you post the entire class
So I take it you're calling the second method currently?
the first
the line i commented out isnt meant to be. It was just to show u what happens when i removed the line that rotates the object
Not sure it matters but is there a reason you're using quaternion instead of Quaternion
no I didn't realise I even had
Try using Quaternion just for giggles
wow no way XD
that fixed it hahahaha
thank you so much, been stuck with this for ages
TIL unity math structs are not compatible with unity engine structs
okay noted, thank you
ah alright. that makes sense. thanks for this, really appreciate your help 🙂
Hey! Hi!
I have a really weird problem: When I'm testing my game on the editor, moving the mouse fastly around the screen makes my performance tank af
And, according to the profiler, it seems to be a problem with the editor?
And, it seems to be correct, because when building the project and testing the same thing there, nothing seems to break.
If anyone knows what to do about this, or needs some extra info/profiler data, idk, please, let me know, I can't work like this.
Btw, I'm using the new input system, if that is useful in any way.
It's apparently a unity editor problem. You need to turn down the polling rate of your mouse
It's really weird. (I also show how using a controller does not affect it)
have you looked at it?
I found that online, but I tried two different mouses, and it doesn't change anything
Are you running any code on mouse move?
Nope, I've already cleaned every part of that, cuz I tought that was the problem
Yes, and to be frank... the code is a big mess! 😄
Try turning off Pixel Perfect in the Canvas
But, let me try changing it from razer's app
Are you trying to grab the object you click, or the object the camera is pointing at?
What do you want to happen when the object is grabbed?
Aaaand that's the problem
Are you trying to grab the object you click, or the object the camera is pointing at?
What do you want to happen when the object is grabbed?
How do I submit a bug?
when object is grabbed, it moves with the camera of the player, it works, but when I dont look at the object that I am currently grabbing, game crashes
@swift falcon
you should only check the grabbing when a mouseclick happens
when you do a mouseclick, you only do a Raycast once. Then, you save that raycastHit, and use it anywhere it's needed during that frame.
That aldo did nothing :/
It's already been reported but it would be https://issuetracker.unity3d.com/
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Yeah it must have been the polling rate
So, my only solution is to change the polling rate, or wait for unity to do something?
Here's what I was playing with, it ended up being quite different from yours and most likely doesn't work perfectly, but maybe you could use it for inspiration
@swift falcon see above
Yup
I will play around and test some thing with it
It's already been reported but it would be https://issuetracker.unity3d.com/
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
It's already been reported but it would be https://issuetracker.unity3d.com/
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
oh
Well, thanks-
oh
basically, raycastHit is the result of a raycast. If you do the same raycast many times, you could just check the same hit property instead
oh
oh
discord moment
you only need to do a new raycast when the situation changes
Is my discord bugged? I see several duplicate messages
API response is slow atm
Fun
I am not sure I understand fully, but if you want the player model to be hidden when it is too close to the camera then it is a shader that you want. (99% sure of that) I am still a beginner in shader, so I can hardly help you.
However, note that doing a clone of an object is NOT a good idea. It will be hard to actually make everythings perfect. (Mainly Animation and Particule Effect). Also, you will not be able to cut the physics mesh. Instead, I suggest that you make an effect from when the player touch the portal that covers the whole player model the time it is between both world and keep the player model out of his camera. (Only the camera of the RenderTexture should see the player).
Is my discord bugged? I see several duplicate messages
Yes. Just wait for it to be over without contributing to the noise
Whats the best way to pause in-game audio when the game is paused? Setting the timescale to 0 does not pause sounds
I usually have an "AudioManager" Singleton type object with a Pause() function that stops all sound
I need help with having my flashlight object stay in my players pov when I rotate the camera. I created an empty object then made it the parent of the flashlight and wrote some code, but it wasn’t working very well. So if anyone knows a simple way to implement this please let me know.
uh is this a code question or ? prob belong in #💻┃code-beginner
Make the player object a parent of flashlight
I already did that and I thought it would work, but it didn’t
Can anyone help explain how is this possible?
public static Dictionary<System.Type, Singleton> Instances = new Dictionary<System.Type, Singleton>();
private void Awake()
{
System.Type thisType = GetType();
if (Instances.ContainsKey(thisType))
Debug.Log(Instances[thisType]); // Error: Key not found
}```
This is in a class "Singleton"
And is being run by a class "Input" which inherits from "Singleton"
Oh wait nvm figured it out, was missing a bang in one of the lines. Silly mistake
I need a sprite animation to play when Time.timeScale is 0, but changing the animator update mode to unscaled time doesn't seem to do anything. Anyone know what I might be doing wrong?
Unscaled time should work. Maybe the animation is not getting triggered at all when timescale is 0?
In the aminator controller window, it has the blue bar to indicate that the animation is triggered, but it's not moving and the animation doesn't play
it freezes like this
Plus, the sprite is set to the first frame of the animation but it never actually plays
Changing the update mode doesn't seem to do anything at all
https://docs.unity3d.com/ScriptReference/Grid.Swizzle.html
What is swizzling?
Swizzles the given position with the given swizzle order.
Looks like it swaps the XYZ coordinates around
https://docs.unity3d.com/ScriptReference/GridLayout.CellSwizzle.html
Don't worry, I was able to get it working by modifying the recursive rendering code to toggle the layer the object was on. Thanks for the suggestion though. I'll still see if that works better than the current system I'm using later on however my shader knowledge is pretty novice as well
thanks.
Another question, one which I cannot find online. How does a value type compare when it stores a reference type? Is this something that should be avoided?
[System.Serializable]
public struct ExitDirectionPair
{
public ExitDirection direction; // enum
public Transform gameobject;
}
That’s perfectly fine. But obviously if you follow that reference the benefit of the struct is void
well how do two instances of this struct compare? Isn't it usually compared via value?
Yes, but for them to be equal, only the reference (memory address stored in the fields) has to be the same. There would be no need to actually look at the referenced object.
yo, i am making a chunk loading system for a personal project, i'm currently instantiating 3 chunks in the direction i go which contain 2500 2D squares each and unload the same amount in the direction i'm not going. So instantiating 7500 times forward, destroy 7500 times backwards.
This creates lag spikes whenever it happens, i want to know what are ways of improving performance?
I have a few ideas like, putting each chunk in a coroutine or making the chunks smaller but i don't see how that is any better (since same number if instantiations need to happen
I'm having trouble working with a singleton in Unity. My PlayerHealth script can't find the gameManager object unless I use "FindObjectOfType" to declare it. However, I thought the point of singletons was that we didn't need to do this? I've seen this style of code online and it seems to work for other people, so I'm not sure what's wrong. Here's my GameManager code: ```public class GameManager : MonoBehaviour
{
public static GameManager gameManager;
//Avoids duplicate game managers
private void Awake()
{
if (gameManager != null && gameManager != this)
{
Destroy(this);
}
else
{
gameManager = this;
}
}
//Logic for when the player loses
public void GameOver()
{
Debug.Log("Game Over");
}
}```
And here's the PlayerHealth code: ```public class PlayerHealth : MonoBehaviour
{
public int maxHealth;
private int health;
private GameManager gameManager;
private void Start()
{
health = maxHealth;
}
public void TakeDamage(int damage)
{
health -= damage;
Debug.Log(health.ToString());
if (health <= 0) {
gameManager.GameOver();
}
}
}```
not Destroy(this);
Destroy(gameObject);
and
GameManager.gameManager.GameOver();
should not have this
private GameManager gameManager;
in PlayerHealth
That last line fixed it, thanks :). So a few questions, what's the difference between "this" and gameObject anyways? Also, when accessing static variables, I guess I just reference the class name itself, so GameManager, and then the gameManager variable I have inside that class, right?
when you Destroy(this) you are destroying the instance of the script. When you Destroy(gameObject) you destroy the complete game object and all it's components
Also, yes, that is correct. to access public static variables it is ClassName.VariableName
which is why for most singletons the variable name is instance
Ah I see, that helps clear things up, thanks!
In BIRP i have to always drop a camera with post stack for the scene to render correctly, is there a way to avoid that? Like copy the stack to SceneView camera, or some global override or anything
maybe i can spawn the camera with hideflags
Can you connect a controller to your unity project?
plug it in, it works
setting it up with old input is pain
people use either new input system or Rewired
How I do that?
do what
Just connecting the control works?
yes unity will detect the controller and you get a message in console that HID device was detected
difficult part is mapping the buttons
lol it works
Hello! I am a new Unity developer, though I have been a developer for a living for many years outside of gaming. I am attempting to make a large open world procedurally generated game as my first game (I know... adventurous, brave, stupid, all of the above). I am running into issues and I think I know the answer, but I wanted a sanity check to ensure I am on the right path.
Info about my process:
I'm using Unity's terrain system
I'm feeding a biome map I created in a map software via JSON to determine biome information
Logic flow:
A. Procedurally generate my starting terrain using a Biome class with primary and secondary biome height and perlin noise ranges
B. Create the next terrain using position of the terrain to the left of it, move through complex weighted chance biome rules using my imported biome map as a basis
C. Stitch the terrains together by modifying the heightmap and procedurally generate the neighbor terrain using the Biome class directives
D. Continue to loop through the terrains handling first row, first column, and surrounding terrain possibilities
My next step was to procedurally paint the textures, detailed objects, etc. as I got to that point but I am at a sang. My world is just too large. I don't want to reduce my size, I just want to come up with the solution to handle it. My world is using 300x261 terrains with a heightmap resolution of 64x64. I realize that this simply can not be done all on one screen. My intention was to save the world to a data file and load the terrains surrounding the player dynamically via individual scenes.
It is looking like my only option is to rewrite my code to save all of this data to some sort of data structure, maybe JSON, and then dynamically load it that way. I was going to have a world save file anyways. I was just trying to avoid that while developing the terrain. Does this sound like my only viable option?
my best advice as you are an experienced developer, do not use Json, use binary save
Yeah I was thinking about that. Heightmap's contain a lot of data which would make for a very large JSON.
json is absolutely crap for game dev
you need to develop a nice modular binary save system
Thank you. I was already starting down this path. I was hoping I wouldn't have to do it yet, but it seems from everything I have looked online, there is no way for me to write/read terrains within scene (even in additive scenes) without the terrains themselves being loaded and that is my problem. I was troubleshooting stitching tears in the upper quadrant of my map and resolved those, but it's just too big to keep iterating through to check to ensure the other parts of the map are okay. Data structure and dynamic loading even while in development of my terrains seem to be the way to go.
yes ive seen it done before by using tree structures, you directly write nodes on disk and read them, and not just the initial state, the actual state is written as well
if you are going to do this, make sure you have adamant redundancies, automatic file backups
When the player presses both movement keys simultaneously, generally what should happen in a 2D platformer?
Do they stop moving or move in the last direction pressed?
good question i just realized i only played those with a controller and it is physically impossible to press both directions on those
wait no on ps one it is possible, nevermind
Hey, cen anyone help me whit walking sounds which detect and object and terrain surface? i cent figure it out how to make so it play only if the player moveing (cent send script bcs its to long) if u cen help please dm me, thanks
yield return new WaitForSeconds(6f);
StartCoroutine(dialogueManager1.StartDialogue(dialogues[0]));
yield return new WaitForSeconds(6f);
Destroy(square);
//
yield return new WaitForSeconds(15f);
StartCoroutine(dialogueManager2.StartDialogue(dialogues[1]));
yield return new WaitForSeconds(10f);
so after Destroy(square) i want to check if my first coroutine has done working, how can i do this?🤔
is this code better than using tags to check for an item?
private void OnTriggerEnter(Collider item)
{
if (item.GetComponent<Consumibles>().ID == 1)
{
HealPlayer(1);
Destroy(item.gameObject);
}
}
You could just yield return StartCoroutine(...) if you need to wait for a coroutine to finish
won't i start it using yield return StartCoroutine()?
Isn't that what I typed?
Yeah it does start it
🤔
If this doesnt work for what you need then you can use a simple bool check
@vocal root theoretically compare int is much faster than string but you have to make sure the component (script) is attached to the GO collided with)
and the engine may propably optimize .comparetag and related memory operations
okey thank you
if (isOnTerrain && movingState.isWalking)
{
// Get the player's position on the terrain
float normalizedX = (currentPosition.x - terrain.transform.position.x) / terrain.terrainData.size.x;
float normalizedZ = (currentPosition.z - terrain.transform.position.z) / terrain.terrainData.size.z;
int terrainTextureIndex = GetMainTexture(normalizedX, normalizedZ);
// Play the walking sound based on the terrain texture
switch (terrainTextureIndex)
{
case 0:
audioSource.clip = grassSound;
break;
case 1:
audioSource.clip = PathSound;
break;
}
}
else
{
// Play the walking sound based on non-terrain surface type
RaycastHit hit;
if (Physics.Raycast(currentPosition, Vector3.down, out hit) && movingState.isWalking)
{
// Check the tag or layer of the object hit by the raycast
if (hit.collider.CompareTag("woodFloor") )
{
audioSource.clip = woodFloor;
}
else if (hit.collider.CompareTag("Carpet") )
{
audioSource.clip = Carpet;
}
}
}
// Play the walking sound
if (!audioSource.isPlaying)
{
audioSource.Play();
}
how in this i cen make when stop walking stop play sound?
I assume you would call audioSource.Stop if movingState.isWalking is false
how do i show and hide variables in the instpector depending on the enum type
With a custom inspector script, or maybe a 3rd party package like NaughtyAttributes:
https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html
Yeah looks like that works with enums. The page has an example for it
thanks
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
but i need make the sound 1 or less second? so its stop instantly?
public class TileTypeManager : MonoBehaviour{
public static TileType STONE, SAND;
private void Awake() {
STONE = gameObject.AddComponent<TileType>();
SAND = gameObject.AddComponent<TileType>();
}
public class TileType : MonoBehaviour {
private TilePool<T> pool;
public TileType() {
pool = gameObject.AddComponent<TilePool<T>>();
}
}
}
i have this TileTypeManager class which holds all my TileTypes
each TileType has a pool with a generic part
i dont want the TileType class to be generic because that just wouldnt make sense but im really struggling to think of how i should do this
any advice would be great
https://gdl.space/uhipunenun.cs
could someone explain to me why the animation isn't playing?
I don't understand why my Visual Studio code doesn't recognize UnityEngine.UI and such
oops i misspelled that when sending the snippet but it still doesnt work
@whole steeple that's actually really weird. what does the error say?
@twin hull It's in french but maybe you can make out what it is with the error codes
a missing reference of some sort
I didn't have that last time I opened my project, so I'm not sure what caused it and how to fix it
Not sure if it is related but Visual Studio Code gives me a prompt that the project hasn't generated the VSCode tools, and that I need to go to External Tools and set VSCode, even though it's already the case
vs code and visual studio community are two separate programs. you have it set to use Visual Studio Community, just use that to code
Ah I wasn't aware they were different. Well I don't have VSCode, and I am using Visual Studio Community.
if (movingState.isWalking)
{
// Play the walking sound
if (!audioSource.isPlaying)
{
audioSource.Play();
}
}
else
{
if (!audioSource.isPlaying)
{
audioSource.Stop();
}
}
WHY THIS DONT STOP SOUND INSTANTLY?
if (!audioSource.isPlaying) twice
(You only try to stop it if it's not playing)
Couldve just removed the ! 🤷♂️
This ended up fixing it :
close Unity
delete all csproj and sln files in your folder
open Unity
always nuke .vs
number 1 cause of most vs related issues
There's now a button for that in Preferences "regenerate project files"
Preferences > External Tools
Wait so if I use a unity relay server to connect peer to peer, and I send a utp message through the relay server, will it end up at the other player’s client
as it is using the UTP protocol, not necessarily
So how would I be able to get a message from the client to the host client and vise versa
if you want guaranteed coms you want TCP or WebSocket protocols
k good to know
is the rest working as supposed to?
UTP is fire and forget. There is absolutely no guarantee it will reach the reciever
nothing to do with resources. Everything to do with FindObjectsOfType. So that is where you should be looking
by looking in your code to where you use FindObjectsOfType
So the stack trace is lying?
NetworkManagerHelper.cs:96
*90
anyone know how to fix it?
other than that typo i dont see errors
maybe you dont have those buttons declared as buttons
Make sure you didn't import UIToolkit buttons instead of the old UI
ah yes
var networkManager = Object.FindObjectOfType<NetworkManager>();
why are you downvoting it? this is literally the code in it
sad ending for a rather good day
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hello, I'm building a combat system for a game that I'm making and I'm stuck on an edge case for my code. Essentially, my game is represented through 2D squares which are individual units. Melee units have an invisible square box in front of them, that's supposed to detect other unit's hitboxes, and begins combat when this "melee engagement" trigger is activated. However, if 2 melee units attack each other frontally, then both OnTriggerEnter method will run, causing a lot of issues as the combat method involves moving the attacking unit relative to the defending unit, and executing this code at the same time causes the units to bug out.
Below is the method for my OnTriggerEnter, which is attached to my "melee engagment" trigger that detects when other units enter its hitbox.
private void OnTriggerEnter2D(Collider2D other)
{
// If the other collider is a unit hitbox, the script isn't detecting a collision with its own unit, and the unit isn't attacking, initiate combat.
if (other.gameObject.CompareTag("Unit Hitbox") && other.gameObject != _parentUnit && !_parentCombatScript.isAttacking)
{
_parentCombatScript.InitiateCombat(other.gameObject);
}
}
Below is my InitateCombat method
public void InitiateCombat(GameObject enemyHitBox)
{
var enemyGameObject = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit;
var enemyMeleeHitBoxDetectorScript = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>();
var side = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().side;
// Set attacking and defending flags and get a reference to the attacking unit.
isAttacking = true;
// Set both units to engaged.
unitScript.SetIsEngaged(true);
enemyGameObject.GetComponent<Unit>().SetIsEngaged(true);
// Disable this unit's collision with the other gameobject
Physics2D.IgnoreCollision(GetComponent<Collider2D>(), enemyGameObject.GetComponent<Collider2D>());
// Disable the other unit's collision with this gameobject.
Physics2D.IgnoreCollision(enemyGameObject.GetComponent<Collider2D>(), GetComponent<Collider2D>());
// Move this unit according to the other unit's position.
transform.position = enemyMeleeHitBoxDetectorScript.GetPositionForAttackingUnit(gameObject);
// Rotate the unit to face the enemy unit.
transform.rotation = enemyMeleeHitBoxDetectorScript.GetRotationForAttackingUnit(gameObject);
// Start the combat coroutine.
StartCoroutine(CombatCoroutine(enemyGameObject, side));
}
can't you just ignore the other unit if you're being attacked already
If an attacker attacks a unit from the side, the defending unit won't attack that unit (as it should), but the issue is when 2 units go head on
unit A overlaps first, so now unit A is attacking unit B
unit B overlaps, but it's being attacked, so it ignores the overlap
unless i'm missing something here?
The question is what do you want them to do when they attack each other head on
Otherwise how do we know how to "fix" it?
Howdy folks. I would like to plan my Unity 2D game to support extensible modding in the future, but am somewhat lost on how one would approach this. I've successfully exposed stats and map design via JSON files that can be edited or replaced. But do any tutorials or how-to's exist for dynamically loading sprites, animations and Prefab type stuff? Given how proprietary/unique these objects are, I can't quite get how to approach adding extensibility for new types of things. I am fine if this effort would be aided through the use of 3rd party APIs or purchased stuff on the Asset Store. And I realize anything would require heavy customization. Just trying to get my arms around it is all 🙂
Addressables are the way to go
This video kinda shows what the issue is. If you look at the top left corner, the red bar is indicating that both units are taking damage. However, you also notice that weird jump both units do when they go head on
Or by dynamically creating objects at runtime from data that is imported as a mod
As in you have a ModdedObject type of class that is extensible, or multiple such as ModdedWeapon etc
I just want to make clear that both of those units are melee units, so they both have that invisible melee engagement trigger, and I believe that both are calling the same OnTriggerEnter methods when they go head on
ScriptableObjects can help with that so that you can just load in custom SOs to an existing object
I'd looked into Addressables, but it seemed like you would need Unity to make the add-ons. My idea was more for the common person to mod things in like you see with Starsector.
You want to fix the positioning jump?
I see, so basically make a new set of objects/scripts that just look in a given place and generate based on what is provided?
Yeah, really depends on what you want modded, and how you want to distribute the content
yea, so in my program, if one of the units attacked another units from the side or the back, that jump wouldn't have occured
Can I see this method --> enemyMeleeHitBoxDetectorScript.GetPositionForAttackingUnit()
When the units attack from the side or back, they just lock in place (which is what they're supposed to do)
ok hold up
public Vector3 GetPositionForAttackingUnit(GameObject attackingUnit)
{
// Get the width and length of the attacking unit.
float attackingUnitWidth = attackingUnit.GetComponent<SpriteRenderer>().bounds.size.x;
float attackingUnitLength = attackingUnit.GetComponent<SpriteRenderer>().bounds.size.y;
return side switch
{
Side.Front => new(unit.transform.position.x, unit.transform.position.y + attackingUnitLength, 0.0f),
Side.Left => new(unit.transform.position.x - attackingUnitWidth, unit.transform.position.y, 0.0f),
Side.Right => new(unit.transform.position.x + attackingUnitWidth, unit.transform.position.y, 0.0f),
Side.Back => new(unit.transform.position.x, unit.transform.position.y - attackingUnitLength, 0.0f),
_ => throw new ArgumentOutOfRangeException()
};
}
So this code is attached to each side of the hitbox for the unit. The unit hitbox isn't the collider for the square, but rather a tiny rectangle representing which side of the unit it's attacking from
Looks to me almost as if the units are moving into each other and then triggering a side hitbox and attacking from the side
As an example, my game has Units of various types. I've defined them each with a Prefab consisting of sprites/animations, extensive set of stat properties, an AI script, sounds and so on. I've already exposed the stats, sounds and some knobs for folks to replace/change. But adding a new one entirely seems tricky. How does one even dynamically build up animations, keyframes and all of that from files/json that players modify in a folder?
See
Yes ur correct I just checked
You would have to create modding tools... I think some sort of SDK for unity would be your best bet similar to how VRChat does it.
This will allow unity to do most of the heavy lifting of importing animations and having them in the "unity" format, and then you can simply package this into an Addressable or something and use it
The top unit is registered as attacking frontally, but the bottom unit is registered as attacking from the left side
In that case one of the units shouldn't move
I've created this method, which is just a stripped down version of the previous InitiateCombat method I posted earlier
public void InitiateCombatWithoutMovement(GameObject enemyHitBox)
{
var enemyGameObject = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit;
var side = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().side;
// Set attacking and defending flags and get a reference to the attacking unit.
isAttacking = true;
// Set both units to engaged.
unitScript.SetIsEngaged(true);
enemyGameObject.GetComponent<Unit>().SetIsEngaged(true);
// Disable this unit's collision with the other gameobject
Physics2D.IgnoreCollision(GetComponent<Collider2D>(), enemyGameObject.GetComponent<Collider2D>());
// Disable the other unit's collision with this gameobject.
Physics2D.IgnoreCollision(enemyGameObject.GetComponent<Collider2D>(), GetComponent<Collider2D>());
// Start the combat coroutine.
StartCoroutine(CombatCoroutine(enemyGameObject, side));
}
///Pseudocode
if(!_attacked)
{
MoveToUnitToAttack();
}
ooooo
as I suggested earier, just break the cycle :p
Yup
now, if you're okay with making a circle of attacking units
you'd need to be more specific: if I'm being attacked by Foo, don't attack Foo
Or expose isAttacking as public and check using the reference to the unit to attack if it is attacking and if so don't move
You've got a bit of a code smell here too
Okay so this is what Ive changed
I've have 3 main properties in my combat script that controls head-on attacks, a public isAttacking bool, a public isDefending bool, and a private reference to the defendingUnit.
I've edited the InitiateCombat method to include the if statements.
public void InitiateCombat(GameObject enemyHitBox)
{
if (isAttacking)
{
Debug.Log($"{gameObject.name} is already attacking {enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit.gameObject.name}");
return;
}
if (isDefending)
{
Debug.Log($"{gameObject.name} is already defending, will attack {enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit.gameObject.name} still.");
InitiateCombatWithoutMovement(enemyHitBox);
return;
}
var enemyGameObject = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit;
var enemyCombatScript = enemyGameObject.GetComponent<Combat>();
var enemyMeleeHitBoxDetectorScript = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>();
var side = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().side;
// Set attacking and defending flags
isAttacking = true;
enemyCombatScript.isDefending = true;
_defendingUnitReference = enemyGameObject;
...
The InitateCombatWithoutMovement works and is functionally similar to the InitiateCombat method, expect it doesn't move nor rotate the unit that script's attached to.
I've also changed my CombatCoroutine to constantly update the flags of the attacker and defender
public IEnumerator CombatCoroutine(GameObject enemyGameObject, Side attackingSide)
{
var enemyUnitScript = enemyGameObject.GetComponent<Unit>();
var enemyCombatScript = enemyGameObject.GetComponent<Combat>();
float dmgMultiplier = attackingSide switch
{
// Front is no multiplier, sides are 10% buff, back is 25% buff
Side.Front => 1.0f,
Side.Left => 2.0f,
Side.Right => 2.0f,
Side.Back => 4.0f,
_ => throw new ArgumentOutOfRangeException()
};
float dmgDealt = unitScript.dmg * dmgMultiplier;
while (!enemyGameObject.IsDestroyed())
{
isAttacking = true;
enemyCombatScript.isDefending = true;
enemyUnitScript.dmgReceived += dmgDealt;
if (enemyUnitScript.dmgReceived >= enemyUnitScript.hp)
{
float excessDmg = enemyUnitScript.dmgReceived - enemyUnitScript.hp;
enemyUnitScript.dmgReceived = excessDmg;
enemyUnitScript.manpower--;
if (enemyUnitScript.manpower <= 0)
{
Destroy(enemyGameObject);
break;
}
}
yield return new WaitForSeconds(1.0f);
}
_defendingUnitReference = null;
isAttacking = false;
unitScript.SetIsEngaged(false);
}
And finally, the script has a OnDestroy event, which uses the defending unit reference to set their isDefending bool to false if the attached gameObject gets destroyed
public void OnDestroy()
{
if (_defendingUnitReference != null)
{
_defendingUnitReference.GetComponent<Combat>().isDefending = false;
}
}
Ok, does it work?
The issue with this code though is that it only works around 50% of the time. Because these methods run near-simultaneously, sometimes both units gets their isDefending bool set to true and both begin attacking without movement
So yea this code still bugged
OKay nvm I figured it out
So basically, I changed one line in the InitiateCombatWithoutMovement method so that it doesn't set the other gameobject as defending
public void InitiateCombatWithoutMovement(GameObject enemyHitBox)
{
var enemyGameObject = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().unit;
var enemyCombatScript = enemyGameObject.GetComponent<Combat>();
var side = enemyHitBox.GetComponent<MeleeHitBoxDetectorController>().side;
// Set attacking and defending flags
isAttacking = true;
_defendingUnitReference = enemyGameObject;
But that still only fixes 1 edge case. If a unit attacks head-on to a unit that's already getting attacked by someone else, this code works. However, if both units are not being attacked, this code will still bug out.
Yea from what I can see the top unit is attacking the unit fine, but the bottom unit somehow registers that it's attacking the unit from the left
Any ideas how I would approach lining up one these quad through its center to the blue dots, when the wheel close to stopping speed?
Is there a way to define how a certain class serializes in Unity's inspector in a separate class?
So I don't need to add a bunch of attributes to the original class everywhere.
Or if I don't have the ability to edit that class.
I mean if I understand your question, Editor scripts can do that
You would probably want to snap to the nearest angle increment after rounding the current angle... Will send pseudocode
var _angle = 360 / spinnerSides;
var _angleMidpoint = _angle + (_angle / 2);
transform.rotation = Quaternion.Euler(RoundedToNearestAngleMidpoint(transform.rotation.x), transform.rotation.y, transform.rotation.z);
Some pretty bad pseudocode but I hope you get the idea
could you explain a little more what would RoundedToNearestAngleMidpoint method internally ?
I can show you my current very basic ass code if you want
if (canSlowDown && wheelSpeed > 0)
{
finished = false;
wheelSpeed -= Time.deltaTime * speedDepleteRatio;
}
wheel.Rotate(wheelSpeed, 0, 0);
Yeah sorry just had to brush teeth
Having trouble with this block of code, specifically with the while statement
seems to be 'decaying' faster than its supposed to.
the goal of this code is to set the bpmCurr value to value, and keep it there for length seconds, then set bpmCurr to decayValue over the course of decay seconds
private float RoundedToNearestAngleMidpoint(float _currentRot) // It was a function just for less code
{
_fraction = _currentRot / _angle;
return (Mathf.Round(_fraction) * _angle) + (_angle/2);
}
Something like this @potent sleet
I think the diagram might not help
Using the current value of bpmCurr as the first argument of the lerp will have a couple strange side-effects. The Lerp will slow down towards the end, and since it's bpmSim cast to an int, it means that the lerp is always starting from the last result rounded down - which in this case means that the lerp is accelerated (a return value from Lerp of 5.9 means the Lerp in the next iteration will use 5 as it's starting value.
I think just using value as your first Lerp argument would solve the issue. But I might think to write it all as such:
float endTime = Time.time + decay;
while ( bpmCurr != decayValue ) {
yield return new WaitForEndOfFrame();
bpmCurr = (int)Mathf.Lerp( value, decayValue, (endTime - Time.time) / decay );
}
i joined this server for literally 5 minutes the only thing i want is how the absolute hell did this guy in a tutorial get the "CameraHolder" thing and how do i get it ive been looking for idk how long please im begging anyone how do i get this
How about scaling the speed based on the difference between the quad behind the line's normal and the desired orientation?
It's unclear what any of those objects are... But he probably just created an empty game object. Right click in the hierarchy > "Create Empty"
(Also not a coding question - this would be more appropriate in #💻┃unity-talk)
can you explain a little how would I approach that ?
I'm actually horrible with rotations/quaternion
the way I'm doing it now is a bit hack, checking array of 20 angles O_O
Hoping this is the right place to put this... But I've recently switched PC and moved my project into a new directory. Everything runs fine, except in visual studio it doesn't recognise the UnityEngine.Rendering.Universal namespace or TMPro. I still have the packages imported, I've tried uninstalling and reinstalling them without success. The project still runs leaving me to believe it's a visual code issue but I haven't found anything online to fix it. Any ideas?
have you tried regenerating the external project files
Preferences (not Project Settings) -> External Tools
Yes, I've tried that. Didn't make a difference :/
var audioSources = _audioSources;
foreach (var audioSource in audioSources)
{
if (audioSource.gameObject.CompareTag("ExcludeFromPause"))
_audioSources.Remove(audioSource);
}
How can I do this without modifying the collection? I'm a bit rusty
I thought using a temporary variable would work but it still throws an exception for modifying the collection
audioSources and _audioSources are the same thing
they reference the same object
one option is to copy the collection
new List<AudioSource>(_audioSources), for example
oh var audiosources = _audiosources is a reference
well, List<T> is a reference type
so any variable of type List<T> is a reference, yes
not to be confused with being a ref
😵💫
var audioSources = new List<AudioSource>(_audioSources);
foreach (var audioSource in audioSources)
{
if (audioSource.gameObject.CompareTag("ExcludeFromPause"))
_audioSources.Remove(audioSource);
}
so like this
That'd work, yeah. A bit clunky, though.
How can it improve?
one option: use LINQ
_audioSources = _audioSources.Where(x => !x.gameObject.CompareTag("ExcludeFromPause")).ToList();
if you really want to be efficient about it, I guess I'd just write a loop that checks each index and removes the item at that index if needed
(and that decrements the index if that happens)
probably not necessary
i've already tested this script with over 4096 audiosources, and at that point the audiosources themselves cause more lag than this script ever could
the worst i could get (before the game was unplayable) was 10ms
Well you know I'm a general noob overall, so this may not work as it does in my head 😁
But when the wheel's speed is "slow enough," I would think to start casting rays from a little in front of the wheel - from right in the center of where you'd like the face to be oriented - towards the wheel, and use the hit normal from there. For rhetoric I'll just assume the desired orientation that a face should stop at is just like Vector3.forward
If the hit normal is angled downwards on the global y axis, it would mean that the face currently in that location has already passed Vector3.forward, and you might start to dampen and reverse the wheel's rotation so it sort of smoothly comes to a rest on that face. Or maybe prevent the wheel's rotation from stopping so it moves on to the next face.
If the hit normal is angled upwards on the y axis, then it's not yet oriented straight forward, and you could do something like
var degreesOffset = Vector3.Angle(hit.normal, Vector.forward);
wheelSpeed *= degreesOffset / angleOfFacesToOneAnother; // Where the latter is the acute angle between two adjacent faces' planes... probably like 18 in the case of 20 faces?
so that the speed will slow down the closer the face is to Vector3.forward, scaling down from whatever it's original speed was beforehand... When hit.normal is aligned with Vector3.forward wheelSpeed will be scaled to 0...
This isn't like super thought out or probably all that would be required, but I hope it helps sort of clear things up a bit?
Edit: though solving it with math instead of physics might be a lot better, especially if it needs to be deterministic I suppose 👀
Use an index for loop as a foreach must explicitly visit every element of the non modified list.
the solution i have now works but ill keep it in mind
You've cloned the list and iterated the clone to remove elements from the original. Memory will eventually have to be freed by the garbage collector.
it is not an issue
Just saying
i already knew that it makes a lotta garbage i even specifically put a comment above the method mentioning that
but ehhhhhh garbage smarbage
anyway is there a way built into unity's UI for me to do something like, if i press the escape (back) button in a menu it presses the back button currently on screen
i've had a lot of trouble ever trying to get the 'navigation' element of UI to work correctly and im not sure if i should be doing this stuff through code or inside of unity
Have them both call the same function rather than a key trigger a ui button.
Yep. There's a cancel event
ICancelHandler
Also the OnCancel thing in EventTrigger
The catch is it only triggers on the currently selected object
I will def consider this possibility so far I have something decent going by using angles ..
yeah , it's a little cringe right now, is very dependent on the array of predetermined angles that I had to set in inspector but. it works.....
I spent way too much time on this already, I will try with raycast at some point though
Thanks for suggestion!
im considering just manually coding this tbh
because i have the problem of a menu with submenus, i dont want pressing escape to close all of the menus at the same time time
i want it to just go back one menu
and the whole "selected object" thing does not really make sense on keyboard and mouse
@wide terrace 🎰 🙂
so do I need to literally put that event on every single UI object
Beautiful! That looks great 🔥
ty
idk what to do here, i thought it would be pretty simple to just have a linear way to progress through the menu with the keyboard
but its impossible to even select a button without clicking it
now add a bunch of anime
and you've got a gacha
Is there any way to make buttons that are being pressed carry over between scenes?
I mean you can call DontDestroyOnLoad(gameObject); in an Awake or Start method which will prevent the game object from being destroyed when the scene changes
Tho something tells me that's not exactly what you're looking for based off of your question
Some more info would probably help
It could work, but I don't understand why "GetButton" doesn't work after loading a scene. Isn't it just checking if that button is held down at that frame?
If you started pressing the run button before the scene change, you need to re press it to be able to run when the scene loads
There's a difference between GetButtonDown and GetButton, GetButtonDown is only true for the first frame the input is pressed, where as GetButton is true every frame
i'm not sure how they behave across a scene transition
I meant to say GetButton
I'm afraid I don't use the old input system much so I'm not sure how else to help
Having some trouble setting up a goomba style enemy in a 2D game. First, I have a Damage script and a Health script for both the enemy and the player, one for them to do damage to other entities, and the other to track health. My issue is, when my player jumps on the enemy to kill it, it still takes damage, and actually takes 3x as much damage as it should! Here's my enemy damage script: ```public class EnemyDamage : MonoBehaviour
{
public int damage;
//Deal damage to the player
private void OnTriggerEnter2D(Collider2D collision)
{
PlayerHealth player = collision.GetComponent<PlayerHealth>();
if (player != null && transform.position.y <= collision.transform.position.y)
{
player.TakeDamage(damage);
}
}
}```
And my player damage script: public class PlayerDamage : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
// Check if the collision is with an enemy
EnemyHealth enemy = collision.collider.GetComponent<EnemyHealth>();
if (enemy != null)
{
// Check if the collision is from above
if (transform.position.y > collision.transform.position.y)
{
// Collision is from above
enemy.TakeDamage();
}
}
}
}```
Hey I have a question regarding pooling design pattern: Is it better to use Stack instead of List to store reusable objects? Or it doesn't matter?
Stack is probably a little easier to work with
since you just use Push and Pop
doesn't matter otherwise
Yep, the same with Queue I guess. But I'm asking about performance, if it's more efficient to use Stack or Queue instead of a List?
no idea. probably doesn't matter
Ah never mind, turns out I fixed it, simply had to switch a less than to a greater than lol. Is this good practice though? Damage and Health in their own scripts?
Alright, thanks!
Yes, that is reasoanble.
it depends on the use case, but unless you're doing an operation many many times per frame i wouldnt really be concerned with this. If you specifically need a stack/queue then might as well use it. If you're going to end up using it to access anything other than the first element i wouldnt bother
itll just be more annoying when u need to access like the 5th element, have to pop and re-add everything
Yes, but for pooling it doesn't matter which element I take
It can be either first or last or from the middle, doesn't matter which one.
well u need the elements to not be in use
When taking an element from the pool it's being removed from that List / Stack / Queue
So if all elements are in use that array is empty
what are u pooling that u need to remove the elements from the list? From the pooling examples ive seen its always just disabling/enabling the object and creating more if no objects are enabled
well, you need to keep track of the objects you have available..
It doesn't matter what I pool, but basically game objects
is it bad to keep track of them by disabling which ones are inactive/available to be spawned? For the example of bullets, I dont see a reason to add them to a new list, because if you dont disable it then it will just be rolling around in the world
To check how many objects I have available I check size of that array
well, you'd also disable them
but surely you must keep a list of the objects that are in the pool
maybe there's a miscommunication here
you're not advocating for not tracking the objects at all, right
i know they must be kept in 1 list, i am asking about storing it in 2 lists: 1 for active and 1 for inactive. Because i thought thats what "?" was asking for
by saying removing them from the list
gotcha
I would have a list that holds pooled (but unused) objects
and then just not have a list of in-use objects at all
those objects must be returned to the pool by some other game system
if you have a list of every object (both waiting in the pool and active in the game), then you'd need to scan through it to find an unused object every time the game asks for an object
i see what you mean, so for example a bullet would add itself back to the pool once its hit something?
right
the pooling system shouldn't need to constantly poke all of its active objects to see if they need to be returned to the pool
guess that makes more sense than looping through the entire list checking if its active lol, i saw a tutorial that did it like this and didnt think otherwise
imagine if the librarian came to your door every hour to ask if you're done reading :p
No need to store active game objects in a separate list. Just a list for pooled objects. Please ping me when replying to me
While it's easy to keep track of pooled objects in a list, it's not easy to keep track of messages by people not mentioning me on Discord
Yep, exactly
Yes, this is also a solution but it's not efficient when you have a lot of pooled objects because iterating over entire list is an O(n) operation
More pooled objects = more frame rate issues, so this approach is good if there are a few pooled objects
Do I sound nerdy? Or something? 
O(no)
I believe librarians have an event listener so whenever a person comes in they invoke it to return the book 🗿
Don't mean to jump over anyone else's question, but does anyone know if there is there a way to run some code slightly before the unity editor play button press kicks in? In a nut shell, my game has a lot of additively loaded scenes, and if one of the secondary scenes is loaded when i hit play (which i do by accident 50% of the time) the game breaks. I just want to check that these extra scenes aren't loaded, and exit play if so.
you can choose from a few different times
I'm not sure when, exactly, would be the right moment for you
Doesn't seem to be a better option than Awake()
maybe i can make my own play button
The default runs after Awake, yes
That's why I mentioned this.
I also ran headlong into that when trying to set up some static stuff before an Awake method ran
the default is AfterSceneLoad, I believe
so maybe implement this to unload unwanted scenes when playmode changes?
So when subscribing a method to it, it will be called before Awake() ?
It's called many times, just filter out the one you want, which is presumably the one before the editor even enters play mode
looks promising, will give this one a go
ooh, that looks good.
ah yes call it
~~sluts ~~slot nights : dating sim
nsfw edition
big tiddi must be included
🤨
🤷 all I see on steam now with anime games
true
responding to the playmodestatechange is almost perfect, except i can't figure out how to unload a scene but keep it in my hierarchy. it just totally blasts it away
Dictionary<TilemapID, Tilemap> savedTilemaps = new();
``````cs
foreach (KeyValuePair<string, Tilemap> b in savedTilemaps)
{
Debug.Log(b.Key);
}
I don't understand why I'm getting the error. It happens when I try to get it like this in a property:
public BoundsInt mapBounds
{
get
{
if (!baked)
{
for (int i = 0; i < tilemaps.Length; i++)
if (tilemaps[i].id == TilemapID.BASE) // id is a string in a struct, contains a tilemap and a string. This part works fine, so please ignore.
return tilemaps[i].tilemap.cellBounds;
}
else if (savedTilemaps[TilemapID.BASE] != null) // when baked is true, it won't work. I don't know why. As you can see above/below, it is logging that there is a key "base" in the dictionary.
{
return savedTilemaps[TilemapID.BASE].cellBounds; // this is converted from TryGetValue, which is why it looks a little weird.
}
return default;
}
}
the error happens before the keys get logged
you're probably doing things in the wrong order
i.e. trying to use the contents of the dictionary before adding them
here's a better screenshot then:
it is clear in this screenshot that it is not the order.
do you have multiple objects with this component on them?
no
Weird problem I'm having: upon instantiating a rigged mesh, sometimes the bones of the skeleton are parented out of order.
Is there a way, maybe through an array, to order all the bones and then have them check if they're in the correct order? I know it'd be a little intensive, but I wouldn't need to run it 100% of the time.
Or maybe "copy the parenting info of this prefab"?
i would not expect the transforms to get rearranged
can you show a screenshot of the hierarchy that shows the difference?
why would the dictionary for the same object return empty then?
I love when people say that. What is "all"? 20 scripts?
The entire script.
that should be self-evident.
it would be nonsensical to ask you to send me every single script in your project.
no, because then there's things in the script that people ask to see because it's not built into unity, like another class, and it just spirals.
that is the entire script.
you have sent three blocks of code
foreach is in an update method, and there's an array of tilemaps (the struct) and a bool for baked. That's it. That's the only part I didn't include.
I gave up on this way anyways, I got it working now.
Does active threads( new Thread()) gets destroyed when switching scenes?
https://hatebin.com/rbnyoqfoyv How can I choose ONLY the selected variables from my enemyType enum at random and then Instantiate them in SpawnEnemy() without having to copy it over and over again for each enemy type. I was thinking I could pass the prefab's name into the function or something but I couldn't figure out how to do that.
your design of Spawner sucks. Delete enemyType. Delete all prefabs. Add serialized array that contains prefabs the spawner will create
well dont delete the actual prefabs
just the hardcoded game object references
yeah I mean the fields :)
Why is it an enum? 
That's literally all I know lmaoooo
Complicating your problem there unnecessarily. If you keep default enum values you can have last enum member as a "count" for collection and use as max value for randomizer. But since you are giving them bitshift values, set their quantity manually and you can generate random number which will tell you how many positions to bitshift to get value from the enum
Wew, people normally learn arrays before enums.
Yeah I only learned about enums because someone here helped me fix a problem by using them and that's basically the only thing of that type I know lol.
enum is not the problem, you are overriding their values to 1,2,4... which are used to keep data compact, for networking for example. Unneeded otherwise.
Isn't bitwise necessary for flags?
I also did that because I asked someone where how I could allow you to select muliple types and they told me to do that
exactly
so to get number 4 you need to shift it 3? times from zero. I rarely use it so might be wrong on how exactly
So to pull value from this enum you need to generate random 1-4 integer which will be used as how many positions to shift so you can access resulting value in enum
so would an array be better?
just remove value overrides and get random number as their default index
Yeah I think so.
Given the purpose.
Then use Random.Range(0, Array.Length) to randomise which enemy spawns.
I would need two arrays as far as I know
because I need to select which ones the spawner uses
And?
then another array for only the ones I actually chose and that array would be the length of however many I chose to random numbers would work
nah I'm just typing my thoughts just in case im wrong
I'm not sure if the first array there is even necessary.
Is it used for a monobehaviour?
Yeah I don't think the first array is necessary at all.
Since you can make a non static variable and set the values.
Since I'm not sure what you can do with it, I suggest you learn Scriptable Objects too.
If i used random.range with the array that I select from in the editor the array could be 5 long, but I only choose two. It would make a number between 1 and 5 which could be any of them

yeah I probably should since that name rings literally no bells lol
That's way too deep thinking.. I wanted casual one lmao
Ok.
I still don't get what the first array is for.
Like is that meant to be global?
Or I guess it's meant to dictate what you can use? 
The first array doesn't sound like it's going to be used.
Uhh man... My code is such a mess I want to wipe out all 400 lines and rewrite again 
the first array is what I use in the editor to select what the spawner spawns, then the second array is made out of ONLY the ones I selected
then I can use random.range on that second array
I mean that's how It makes sense in my head
In one class or one method?
If I use random.range on the first array (which we'll say is 5 elements), it'll give me a number between 1 and 5
this wouldn't work if I only selected two things
10 abilities added in a single class and many of them interfering with each other.
Everything is glued together using copium. If I find a bug and have to change one thing then the entire functionality breaks
I guess I won't ask further about that.
Are their data types the same?
J
Ok it's sending finally.
im fairly sure? it's just going to store prefabs. or gameobjects or whatever
Is this still about spawning a random npc from a list?
yeah
have u made that array or list yet?
Yeah unrelated but learn Scriptable Objects when you can, that helps you cut down on prefabs.
why do you mean by scriptable objects
Yeah we were talking about how it's going to be used.
scriptable objects wouldnt help u if each enemy is different in terms of models
You really have to search that. Idk how to explain it.
I haven't opened unity in a second so I really haven't made the arrays yet
im playing games with friends and I don't want to just not respond to you guys
honestly i dont even know what u mean by telling him to use SO. Unless all these enemies only differ by stats
Isn't scriptable objects used for data? How does it reduce prefabs tho
they do
I have one script called "Enemy" that I put on each prefab. Each enemy prefab is a little different and has a different model and im just spawning those prefabs
SO wont help u then if the model is different
yeah different enemies different models
some data can be stored in an SO, but really i wouldnt worry about that rn
all u need is an array/list of game object, use [SerializeField] then drag them in through the inspector. Randomly select an int (0, number of prefabs) and spawn that
His question extends to which of those elements in the array can be used.
dont store the ones u cant use..
once again im still confused. If you have a list of 5 prefabs, and then only select two out of that list, using random.range on that list will provide a number between 1 and 5, not between the two that you select in the editor
Anyways.
Make a new class that doesn't inherit to monobehaviour.
Add [Serializable] on top of it.
The only contents should be the Enemy prefab.
And a Boolean on_use or something.
Make an array out of that class. That should do your first array.
what do u mean "only select two out of that list"? Where does this 2 come from, and why are u thinking of storing all 5 if u dont need all 5?
I think my explanation isn't coming out right
explain what u want to happen in your game, not in code
For the second array which is the enemy prefab add [HideInInspector] leave it be.
On Start of the Spawner script, make an List<Enemy or smth>
Foreach( element in first array) add
If element.on_use == true Lists.Add(element.enemy)
I want one spawner to be able to spawn for instance, a shotgunner, or a machinegunner.
Then, a different spawner could be spawning a flying orb and a tanak
Ok so only store the shotgunner and machinegunner on spawner 1.
you dont need 2 arrays
now I think you're misunderstanding me
how do you think it would work with only one array
Each game object on game menu is an instance.
if u need a 3rd spawner, are u going to make a 3rd array?
no that's not what im saying
Each values in that instance can be different.
not at all
2 arrays, any number of spawners
each spawner just has the same script attached, which happens to have 2 arrays in it
u havent even tried this with 1 array, why do u have 2
because two is the only way it works in my head
u were also encouraging their idea of 2 arrays
why wouldn't two arrays work though???
one for the initial selection, then one that random.range will use
I can't bother asking any further after I already did.
even IF you select only two out of the array, Random.Range will still return something between 1 and the list length, not just a number based on only how many you selected
that's why you make the second array which is only the ones you've selected out of the first array so random.range will get only those
here i made 2 spawner objects, and both have the same script on it with 1 array only.
[SerializeField] List<GameObject> spawnableObjects = new();
Notice how both spawners have whatever they want
We didn't say it won't, we just say it's unnecessary.
what is "just a number based on only how many you selected"
What am i selecting
and why have 2 arrays if u dont plan to use the first
I was thinking it would work like a drop-down list like an enum, not like that where you just add the ones you want
Thats a bad idea really for this
I didn't know that you could just add only the ones you want to the array like that in the editor
well that's the only Idea I had because I didn't know that arrays did it like your image
before you sent that Image I was still under the assumption that arrays showed up in the editor like an enum
Well, unity can display any field on editor except delegates. Just a rule of thumb I guess.
ill simplify a bit: both objects, spawner1 and 2, are unique so they both have their own array stored. The arrays are not related to each other and know nothing about each other
When you used enums, you were providing it the same enum so it will always have every single option
every single option which you could choose between for each spawner
yes I know that now I'm saying that you're right and I just wasn't sure of how exactly an array worked
there were more problems with your enum other than that as well. It just doesnt make sense to use especially with it each enum value being 2^n. You would be limited to 32 things to spawn max
alongside just that your enum would then have to look up the prefab
in this case, the prefab is directly accessed
You can inherit an enum from Long and you'd have more choices right?
so how exactly did you set up that script you've got there?
i think u need to cast it, but just not a good idea for this regardless
public class SpawnerExample : MonoBehaviour
{
[SerializeField] List<GameObject> spawnableObjects = new();
}
i didnt write anything to actually spawn the objects, just showed how this works in inspector
oh speaking of that I should probably change a lot of my public variables to privates with [SerializeField]
Why not an array? 
why an array
wait so is that not an array?
Why a list? I personally just use array if I know I won't add or remove another element to it.
its a list, it will be almost identical. The only difference is u dont have to worry about resizing a list
I was calling it an array this whole time I don't even know where I am im lost lol
because any reasons people will justify in this case for list/array are so insignificant that theres no reason to choose one or the other
List is a list. Array is when you have [] next to the type
As a rule of thumb, array is anything that has a [] on the end of the type.
You still use brackets to access the index on list or arrays though.
Every time I come to this server I only understand like every third word said and it never gets better 😭
Yeah demonstration via code block would be good.
well u havent used arrays or lists yet, itll be understandable when u experiment
But I'm nn phone.
Might as well show the necessities like getting the index or how to add an element to a list.
Also Arrays and List starts from 0, not 1.
they'll experiment and figure it out 🙂
thats how u learn to get familiar with new things
This is why I would rather read docs or watch yt vids than ask here. 
I did so much searching on how to do it with enums before asking here because I didn't really know that lists could do it a million times better
well yea, thats how u learn. People ask here about things they cant find online, like if you just need advice on what an algorithm is called
or when things are just really obscure and you have to hope someone had the same issue as u lol
Wew
I asked for and deep copy code that works with unity objects.
I didn't get my answer tho.
I at least found some guy that made a recursive memberwise clone and I just yoinked that stuff. 
honestly dont know why u would ever need a deep copy
hello everyone... I am getting a "UnauthorizedAccessException" error:
//string var has its value now
File.WriteAllText(Application.absoluteURL + "/textFile.txt", stringVar);
"Access to the path "C:\textFile.txt" is denied."
as you can see I used absoluteURL... i dont know what's the cause of this
You dont need to specify such a url, also you shouldnt be writing directly to the C drive
I remember applicationurl gives me a specific folder (which is not in C) I dont know why the application is going there
absoluteURL is not for that purpose. You're thinking of persistentDataPath
oh
yes
thank you
Default company folder 😎
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
@lean sail It's normal to use interfaces and delegates to get around assembly definitions right? 
Hey,
I have issue with 2D Colliders sometimes doesn't work when move fast. Video here: https://youtu.be/fO967SY2h8Q
Basically I want to rotate the Maze (green thing) and lead the ball to somewhere inside the maze.
this is the code I use to rotate the Maze:
var rotationAngle = Time.deltaTime * rotateSpeed * playerInput;
var rotationDelta = Quaternion.Euler(Vector3.forward * rotationAngle);
rbList.ForEach(rb =>
{
var relativePosition = rb.position - (Vector2)transform.position;
var rotatedRelativePosition = rotationDelta * relativePosition;
var newPosition = transform.position + rotatedRelativePosition;
rb.MovePosition(newPosition);
rb.MoveRotation(rb.rotation + rotationAngle);
});```
@hollow pelican Take a pic of the collider component to please. 
here is for the maze.
here for the ball:
I think I remember how to fix it, but go to look at collision detection, and set it to continuous.
Try doing it for the ball only.
If there's no such option or it doesn't work, idk.
yes, the ball as "Continuous"
i have tried to tweak the Time also, but the issue still happen
Yeah idk. 
i havent done anything specific with assembly definitions, so not really too sure what you're doing
try setting the maze tiles to be continous speculative
Trying to separate the entities and weaponry to different assemblies. And weaponry kinda needs to gather a few things from entities. 
Is there any reason PrefabUtility.InstantiatePrefab(edgePrefab, transform) would return null? Like not throwing an error, but returning a null object?
Ah figured it out. I had an object in scene of the prefab, so I saw the prefabs name and thought it was selecting a prefab.
transform.position = Vector2.Lerp(transform.position, targetPosition, percentageComplete);
i want only the x component of transform.position to lerp how to do that?
Don't crosspost your question
aight
I use Unity 2022.2.20, there are onely 2 options: Discrete and Continous
Oh it's probably due to it being 2d
yes, it's 2D
Try setting interpolate then, maybe on both the ball and maze if they're both moving fast
If interpolate doesnt work, I'd play frame by frame and see what's exactly happening with the collisions.
Are u moving this in update or fixed update
it's on FIxedUpdate()
Interpolate should be set on the object that move fast?
Typically it's just for the player character to smooth out jittery looking movement
doesnt work :), i tried to set Interpolate on each one and then both, still have the issue
If none of the settings work, then you are likely moving something based on frame rate
Continuous alone really shouldve solved it
Is there a best practice setup for sending information between scenes? For example after a battle I want to output the result of the battle to the next scene, so it can be used to correctly alter the game state of the main game field.
I can think of a bunch of dirty methods using static variables etc but it seems a bit dirty.
sorry, i dont really get this one. Can you elaborate more ? 🙂
if anyone here knows disco zoo, do u think the animals fitting in the grid is an algorithm? or based on predefined options and locations?
Heyy, Eulers are pretty confusing.
I have object A, with a local rotation to a parent.
And object B which is a child of a scene
I want to set rotation of object B, same as object A
Should i use transform.Rotation, or Eulers?
It might be possible one value is based on fps rather than just using physics. Maybe something to do with transform.position instead of rigidbody positions Though it's hard to tell from the code u sent. I'm not too knowledgeable about the physics system
Yep, I use deltaTime for it, and the maze is Kinematic
hey
Both should work. Eulers just get converted into rotation (Quaternion).
how do I rotate a single bone in an animation from code?
I just want to orientate the moving animation towards the direction
Rotate it like any other transform, but do it in LateUpdate so it happens after animations. If it has an Animator, that is
right, I'm using the humanoid skeleton type, so if I rotate the hips it will rotate the legs too right?
Yes
thanks
got another question
I'm using this method to get an angle of my character compared to movement direction
var velocity = PlayerController.RB_Main.velocity.normalized;
var charTransform = PlayerController.CharacterTransform;
float angle = Vector3.Angle(velocity, charTransform.forward);
return angle;
but my problem is that the angle is always positive
how can I get a negative and positive angle
like if I look towards left from direction it should be negative
Did you have a look at the Vector3 docs?
no I didn't
Checking the docs should be the first thing you do when having a question like that.
sure
He meant the way you move the objects.
There's two ways I know of, one is transform.position which is literally displacing them and setting the velocity of the rigid body which lets Unity do some physics on it.
how do i set chromatic aberration weight in volume component through script
It guides you through how to get to volume overrides and then how to access different parameters
You would need to TryGet the chromatic aberration override
ohh
ty
👍
show the whole line and the error
Use the one your pipeline uses
why do you have URP, HDRP, and PostProcessingStack installed?
which one are you actually using?
Also how are you getting the volume component
then use the URP version of everything, make sure you aren't using the wrong namespaces. You are currently trying to use the PostProcessingStack ChromaticAberration but you need the URP one
As in .sharedProfile or .profile
.profile
im using this is it the right one for urp
no, I mean in code
oh
the volume holds Rendering.Universal post processing effects if you are using URP, which is this one
^^
alr
can this ever return null? I'm pretty sure Application.dataPath always has parent. or this isn't what rider is pointing out?
I dont think rider would analyze that deep, it's just warning you that technically GetParent can return null, even though that might be impossible in this case
you could suppress the warning
oh ok
its giving me this error for the tryget line
are you sure you properly dragged the volume component into your serialized variable in the inspector?
and if so, are you sure you don't have multiple of these scripts in the scene where one of the scripts could have nothing dragged in?
ah
ok it works now ty 
you could suppress the warning
TIL that instead of?which is doing null check I can just write!which suppresses the warning
I have 2 objects.
Object A : is child of the scene
Object B : is child of many parents, each parent has its own local rotation to higher parents
I want to set rotation of object A = rotation of object B So in the scene they would be equally rotated
After several failed attempts i couldnt execute this in code, could someone help me
yeah, that is much more widely used on more modern C# projects since they are doing a bunch of "null explicitness"
in newer versions of C# I mean. They really want the programmers to be aware of when things can or can't be null
null explicitness? new term for me 😄
that's because I just made it up (I just mean they are forcing people to write ! and ? all over the place, i.e. be explicit)
can you show your most recent attempt?
and describe what goes wrong?
i.e. be explicit
ah I understand, ty
is C# 9 considered newer version?
or modern*
C# 11 is current
maybe I should have provided some context, that ! is you telling the computer that you know it will not return null. It just happens to also supress the warning as a result
C# 12 will come out end of year
but why is unity so behind?!
because it uses mono and IL2CPP in the backend instead of the .net runtime
don't quite see relation between .net runtime, mono, il2cpp and language version 😄
tldr; it takes a lot of effort to support the new IL standards
mono is a copy of .net runtime, but not as good, and il2cpp converts .net bytecode into C++ then compiles it to machine code
unity is still behind because it takes a ton of effort to rewrite IL2CPP I'm sure
I see, thanks 🙂
for some reference, it should just be this:
objectA.transform.rotation = objectB.transform.rotation;
if that doesn't work, then you might have another script that is interfering / causing the issue
Sure, so the ultimate goal is to instantiate a bullet, which is a child of the scene
Then, there is a gun, which consists of several parts (parents) each with their own rotation relative to other parents
When firing (instantiating) the bullet, i want to instantiate it at the same rotation as the gun barrel.
(Note: after instantiating, i set rigid velocity to forward)
Problem: after trying to use Euler Angles, local rotation, and everything i could think of. The bullet kept coming out at a different angle than the gun barrel, and wasnt moving exacly forward (direcly towards blue Z arrow)
GameObject Bullet = Instantiate(BulletObj, GunBarrel.transform.position, GunBarrel.transform.rotation);
are you sure your bullet isnt just hitting your player collider?
or something along those lines?
because, right now, that code looks fine
I set it to isolated collision layer. I also forgot to mention that the bullet doesnt even spawn at the same position as the barrel,
ill have to go throught it, thx a ton anyway
well, after instantiating, log the position of the gun barrel and the position of the bullet
you should see that they are identical
so yeah I would check through everything and make sure something else isnt moving it after, but I can assume that its something to do with the physics
I need to negative array index for procedural map generation and i make this class, is that good?
class MArray<T>
{
private T[,] _Array;
Vector2Int zero;
public MArray(int x,int y)
{
_Array = new T[x * 2 - 1,y * 2 -1];
zero = zeroPoint();
}
public T this[int x,int y]
{
get
{
return _Array[zero.x + x,zero.y + y];
}
set
{
_Array[zero.x + x, zero.y + y] = value;
}
}
Vector2Int zeroPoint()
{
int x = ((_Array.GetLength(0) - 2) / 2) + 1;
int y = ((_Array.GetLength(1) - 2) / 2) + 1;
return new Vector2Int();
}
}```
your zeroPoint method will always return 0,0, and your array dimensions are a bit confusing (I dont think you should be subtracting 1)
zero point is center of array in my case
your zeroPoint method returns 0,0 because you aren't actually using the X and Y variables you created
You can just set zero.x to x and zero.y to y (or there maybe a +1
Yes i can this is good idea 😄
No, there is no +1 term
this thing has a problem (it's not really a big problem) because of its logic that it can't create an array of even number sizes
I just wouldn't offset the internal array
instead, I would do calculations when I am trying to index the array with a position or something
and the calculations would turn the position into an array index
[0,x-1) x-1 [x,2x-1)
0 needed to be mapped to x-1 so zero.x=x-1
there is a 5,5 MArray example (x and y swapped xd)
that's why i did
Wouldn't that only have -4,-4
they double their size inputs for some reason so it would actually have -9 -9
its more like an extents parameter
I see
array size is calculated based on distance traveled from point 0
zero point is also counting
I have done some array similar to your case but i use a offset pointer
yes actual size is 9,9 array
what was the question again? this seems to work for what you want
sorry I just wanted to discuss this thing
It seems to serve as an calculating layer in terms of converting world positions to grid array positions that I will be using for chuck and voxels loading system.
If the T is struct then you cannot directly modify the members of struct
So i use unsafe list and pointer
🥵 then i use class for variables
Will this cause a possible memory problem?
class/struct is relevant to how and where memory is managed (and usage), and irrelevant to memory consumption
@cursive gorge https://www.c-sharpcorner.com/blogs/difference-between-struct-and-class-in-c-sharp
there's a neat article about it
I thought like this: Since classes are more complex, memory management and access will be a bit more problematic, but because the struct only carries variables, it is lighter.
it's not problematic, it's different
Thanks
classes are reference types, which means all you store in your variable is just a pointer
which means almost free passing around
structs are value types, which means you actually store your value in your variable
I think this whole lightweight vs highweight comparison is pretty much irrelevant
they are just different
Hmm i dont familiar with how memory access variables but i guess i get it, thanks
Lightweight vs heavyweight is not entirely irrelevant. If you make most of your class variables structs(where they could be a reference type), your classes would consume more memory. It depends on how heavy your structs too, but if, let's say, you need the same data to be accessed in 2 classes and you use structs for that data(sync it by copying it around or something), then you technically consume twice as much memory as you could if you were using a class.
It's not as simple of course, but the gist of it: use the appropriate data structure.
but it's not like you can just unceremoneously change class to struct and get free memory 😄
they have different usage and different purpose. you don't change class to struct because it's "more lightweight", but for entirely other reasons
You could.🤷♂️
Or you could be obsessed with structs and only use them from the very start. That's the situation that I'm trying to warn against.
well as you pointed out, struct can be higher weight depending on usage, that's why I advise against comparing them by this "weight", instead I think one should consider more exact and detailed differences, such as value vs reference, managed vs unmanaged, heap vs stack, pitfalls when passing them in and out of methods, etc
because applying paradigm "struct is lighter" we might (and will) end up just assuming struct is better when it's ever applicable, which is just wrong
You can certainly cause more performance problems by using structs without understanding how they're allocated and when, vs just using classes
hey guys, i am working on a project where i have to load prefabs online into my app
and i am using asset bundle for that, its downloading alright but i need to know how can I keep the model downloaded and if i open it a second time it should load from cache or anywhere without internet, i believe it's simple question i am just not able to find any source which does it, can anyone help on this
please help stuck on for 2 days now 🥲
Hi guys, I don't know where to ask this issue...
My entire Unity project 2d start to go very slow, between 2-9 fps.
The project is really soft so I don't know why its so slow
Somebody could help me please?
use the profiler
Window > Analysis > Profiler
run the game for a bit. you'll see a line graph up top. click anywhere in that to pause and examine that frame
probably need to store it inside a folder inside Application.persistentDataPath
haven't used asset bundle much though so take it with grain of salt
Thanks
one thing that comes to mind
i made this mistake several times
i would export a model from Blender and forget to exclude the camera that was in the scene
Unity would say "oh, you want a camera?" and create a camera for every single instance of that model
game grinds to a halt
(also when I don't run the game, the engine is VERY slow)
do you open many editors?
like 2 fps
Ahhhm I have opened another unity project in this time
2 project open
I just closed it but nothing
The problem started after I have imported some audio
Quick question. Anyone know if it is possible to force raycast a disabled collider?
Seriously doubt it. Pretty sure disabling will remove the PhysX collider, so there's nothing there to hit.
Yeah, that is what I was figuring it does. But thought there was a chance of some utility method or enum or something that might do it that I just wasn't finding. Thanks for the conformation 🙂
I use this assets to get folder path https://assetstore.unity.com/packages/tools/gui/runtime-file-browser-113006 and this code to load audios, some mp3 files give infinite error loop ```csharp
IEnumerator loadSong( GameObject obj )
{
FileSystemEntry song = getSong( obj.GetComponentInChildren<TextMeshProUGUI>().text );
if ( song.Path != null )
{
AudioClip audioClip = getAudioClip( song.Name );
if ( !audioClip )
{
loadingObj.SetActive( true );
using ( UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip( song.Path, AudioType.UNKNOWN ) )
{
yield return request.SendWebRequest();
if ( request.result == UnityWebRequest.Result.Success )
{
AudioClip requestClip = DownloadHandlerAudioClip.GetContent( request );
requestClip.name = song.Name;
if ( requestClip.length > 0 ) songClips.Add( requestClip );
}
else
{
Debug.Log( "Error loading audio: " + request.error );
}
}
loadingObj.SetActive( false );
yield return null;
StartCoroutine( loadSong( obj ) );
}
else
{
ResetUI();
Toggle songToggle = obj.transform.GetComponentInChildren<Toggle>();
audioSource.clip = audioClip;
songToggle.isOn = true;
audioSource.Play();
}
}
yield return null;
}```
This line >>> AudioClip requestClip = DownloadHandlerAudioClip.GetContent( request ); gives infinite error loop
Im not sure how to avoid that I've tried try{}catch but nothing
what do you mean by "infinite error loop"?
share actual errors etc.
gimme a sec to recover the error
this infinite error loop Error: Cannot create FMOD::Sound instance for clip "" (FMOD error: Unsupported file or audio format. ) UnityEngine.Networking.DownloadHandlerAudioClip:GetContent (UnityEngine.Networking.UnityWebRequest) MusicFolderScanner/<loadSong>d__17:MoveNext () (at Assets/_Assets/_Scripts/_Menu/MusicFolderScanner.cs:155) UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)
The audio format is mp3
This happens with some audios and the other load fine
what do you mean by "infinite" error. I'd say the reason you're getting the rror overr and over again is because you are calling the coroutine recursively:
StartCoroutine( loadSong( obj ) );
For example this audio gives error you can test for yourself
I'd guess the audio file for that particular clip is corrupted or otherwise unsupported by Unity
So you are able to load some mp3, but not others?
thats right
Then there's probably some feature of the MP3 file format being used in those files that Unity doesn't support.
ah your right lemme fix that
You can look into using NLayer to convert the MP3s to PCM/float[] samples, which you can then feed into AudioClip.SetData.
I will look into it and see thank you!
A file in MP3 format could be encoded many different ways. The encoding could be different on this one
you might be right I think I used some page to mp3 download I dont remember exactly
Try re-encoding it in Audacity
I changed this line and now the error only shows once csharp if ( requestClip.length > 0 ) { songClips.Add( requestClip ); StartCoroutine( loadSong( obj ) ); }
so none of this has anything to do with try/catch or infinite loops
you just have an #🔊┃audio problem
your clip/file is not supported by unity for some reason
and how I can let a user know that their audio doesnt work if it gives that error?
up to you
show a UI element with an error message?
Have a little creature jump up and say something to them?
whatever you want.
Try/catch is a good way to detect the error
assuming it actually throws an exception
it's unclear if it does
if I put an else statement in that last line it should work I guess
If that works then it's not actually throwing an exception
in which case yeah, that's fine
Bruh even audacity doesn't recognize the audio
Cant imagine many things would work with a corrupt file
doing what it says there is just static
The thing is in a windows audio player it works fine
can u try converting it to wav?
Let me use a page converter to see if it works
it might just be some format used that audacity/unity doesnt accept
theres probably a site u can see what it really is, idk much about audio but it should have information in some header
It appears to be a mpeg-4 aac codec... I can only find mentions in the Unity docs of supporting mpeg 1-3. From a Unity rep on the forums in 2021:
the last time I checked, mp4a was not supported. So even if it happens to work on some platforms, we don't support it across all of them.
with .wav it works
Is there a way to check if the audio is mpeg-4codec?
That way I dont get that error
probably a site online
on audacity forums people say use this one https://mediaarea.net/MediaInfoOnline
it says 2 / 40 / mp4a-40-2
mp4a is the part u care about there then
Is there an extension or plugin I can use in unity to auto convert this to mp3 or wav so I dont get that error?
You could probably package up ffmpeg/ffprobe with your game and use it to determine codecs, or even convert the file on the fly... I have no idea how large of a headache that might be though 😁
There's probably something on the asset store which does so - I'd search "ffmpeg"
How can I clone a NavMeshData? I want to have two copies which are different objects.
Basically, I want to be able to do:
NavMesh.AddNavMeshData(data, positionA, rotationA);
NavMesh.AddNavMeshData(data, positionB, rotationB);
However, I noticed that if both datas are the same object, only the last data is added.
So I need a way to clone it.
you could make it yourself for specific file types, and kinda just ignore stuff like mp4 or ogg
still how I can check if it is mp4
Seems this gets skipped private string[] validExtensions = { ".wav", ".mp3", ".ogg", ".aif", ".aiff", ".flac" };
well idk where u use that in your code
Luckily, NavMeshData is a UnityEngine.Object, so you should be able to use Object.Instantiate on it to clone it.
chatgpt sayd to convert it use ```csharp
using NAudio.Wave;
using System.IO;
public class AudioConverter : MonoBehaviour
{
public string inputFile;
public string outputFile;
void Start()
{
ConvertToMp3(inputFile, outputFile);
}
void ConvertToMp3(string inputFilePath, string outputFilePath)
{
using (var reader = new MediaFoundationReader(inputFilePath))
{
WaveFileWriter.CreateWaveFile(outputFilePath, reader);
}
}
}
chatgpt
When I use instantiate, only the last NavMesh.AddNavMeshData is shown in the scene view. So I think they are still sharing some internal state
Hey chatgpt is good in some aspects but sometimes fail
well first see if u can even use NAudio.Wave whatever that is.
Theres literally examples online though if you search for converting files in c#
ive only done it in other languages so i cant really suggest a c# method for it
Okay now that I know the issue I will search
system io will help u get the path extension if that was an issue
nah the path is fine I use a file browser to get the folder then add the filename after
i mean file extension*
it was just the audio format that it gave error
File extensions are not indicative of encoding (thus your mp4 with a .mp3 extension). If you want to know how an audio file's actually encoded, you need to create or use something which is capable of reading the encoding metadata from the file.
the data should just be at the start, and you'll be able to find how many bytes it is online
with NAudio it gives this error I used audio importer asset csharp Got a frame at sample rate 44100, in an MP3 with sample rate 11025. Mp3FileReader does not support sample rate changes. UnityEngine.Debug:LogError (object) ImporterExample/<Import>d__5:MoveNext () (at Assets/AudioImporter/Examples/ImporterExample.cs:30) UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)
