#archived-code-general
1 messages ยท Page 32 of 1
probably yeah
I don't use either now though because I realised I just needed to use - lol
I was overcomplicating it
I understand the concern about performance - but yeah, the difference you will get between this, and whatever you could come up with to avoid an extra cast, is basically none.
division by 2 is extremely quick - same as int >> 1
this is a little bit off topic but where can I find good artwork for the background of my game?
kinda just looking for anything
multiplying by 0.5 could probably be even slower lol
since a divison by 2 is just 1 right binary shift and tits super fast
if you divinding by like 3.14159265 then division becomes slower, but dividing anything by a power of 2 is super fast
you doing that just makes it slower and makes the code look bad
Though after that I changed it to this because I realised I didn't need / heh
How would I make my A* enemy jump over gaps?
Or is there a way I can use Unity's NavMesh in 2D?
If it's a certain weight, then jump?
Afaik, no
But right now it doesn't detect gaps
I'm trying to figure out a method for it to detect gaps, but the ones I come up with are a hit or miss
Well I think A* uses weight, so maybe you can predefine a certain weight or smth, or have it so that when it collides with a certain tile it'll run a jump animation
The latter is probably the easiest
Yo, any way to check for objects being rendered by a specific camera?
Probably, 


I mostly check unity docs
and I quite did but I also added in "without raycasts" so I only got results about raycasts
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.
Well, my issue is that I don't want to have to predefine every single gap
But for now, I'll look into the weight thing
this is fairly complicated, you would need to have a cost for jumping over gaps and extend the neighbor search functionality to check the opposing side of the gap from where the current node is during pathfinding iteration
It depends how optimally and realistic you want to have it
if the gap can be more than 1 tile wide, and you need to be able to jump to any tile across the gap (not necessarily just cardinal directions), then good luck lol
Because I assumed that the character can jump any gap, but that's probably not what you want
Pathing isn't that easy
you might be able to add a new type of node called an "edge" that borders gaps, and when you encounter an "edge" you have some custom pathfinding logic that adds nodes to the open / closed lists based on whatever your conditions are. Like, it could add nodes to the open list if they are within 2 tiles of the origin edge, etc
Would it be easier to make it stop if its going to fall to its death?
what do you mean?
shouldn't that happen automatically since it would, by default, path around gaps?
No, it currently will just continue to follow the player and fall to its death
I do
Technically, yes
It's a heavily modified version of someone else's own A* script
I used it because when I used the AILerp script, my enemy would just float to the player
But I want it to be a grounded enemy
well then, I will say that it would be very difficult to make enemies jump over gaps + include that in the pathfinding if it's not a completely custom pathfinding solution
I think the easiest way would be to fake it, like Wumpie said
you should be able to automatically tag "edges" around gaps with something
and if you encounter those edges, you step through the path via nodes and find the first non-gap node in the remaining path
then you play a jump animation from the start edge to the end edge, on the other side of the gap
you would leave gaps as walkable for this to work
but this also means you don't have much control over the length of gaps that can be jumped over, etc
they would be able to jump over a gap of any length
Hello
i have player which moves Top Left down and right (2D Topdown withought diagonal).
So the Problem is that i have also a Tilemap and i want the Player to kind of Snaps on Middle X and Y of the Tiles in the TileMap.
My code:
private void updateMovement()
{
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
if (Mathf.Abs(horizontal) > Mathf.Abs(vertical))
{
vertical = 0f;
}
else
{
horizontal = 0f;
}
animator.SetFloat("hori", horizontal);
animator.SetFloat("vert", vertical);
Vector2 direction = new Vector2(horizontal, vertical);
transform.position += (Vector3)(direction * maxSpeed * Time.deltaTime);
//updateHookPos();
}
lets Say we have a Tile 32 x 32 and i move the player to the left then he has kind of snap softly to the middle Of Y-Axe
Any Idea?
Kind of like this:
Xd
Do you think I could detect the edge by getting the current object the enemy is colliding with and setting the edges to the left and right bounds of the collider?
And then maybe I could have a raycast coming out from the ground to see if another ground is within a certain distance
!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.
yeah u can do that
outch sry
you can just check the position of the player and set it to the closest value with is a multiple of 32, if that's what you want
rivate void updateMovement()
{
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
if (Mathf.Abs(horizontal) > Mathf.Abs(vertical))
{
vertical = 0f;
}
else
{
horizontal = 0f;
}
animator.SetFloat("hori", horizontal);
animator.SetFloat("vert", vertical);
Vector2 direction = new Vector2(horizontal, vertical);
transform.position += (Vector3)(direction * maxSpeed * Time.deltaTime);
//updateHookPos();
}
could u give me a small example? like under vertical do i have to do that snap?
!cs
you want it to snap only on vertical?
no and Horizontal depends on the mOvement like when u go to left and right it snap vertically and top and down snaps horizonatly
int rem = val % 32;
int result = val - rem;
if (rem >= 16)
result += 32;
this should work
change result instead to your x or y position
wait can u modify the code with that? ^^
ok thx ^^ iw8
do you want it always snapped on the grid
or what
i dont 100% understand what you want to fully do
like softly snapping while moving? is it possiable
like with time.delta time while moving u k
^^
after you stop moving?
hmm
so you dont want it to hard snap, you want it to slowly shift to the nearest grid and not instantly
example:
u r not snapping and u r on the 10pixel so while moving it incress to 16 because u k is the middle
exactly ^^
can u answer my question
which one ^^
this
yes ^^
both x and y?
depends on the movement u go right or left then its snaps on Y and top or down it snaps to X
sry Xd the problem when u use a German Layout Xd
How do I simulate user input in unity?
float NextSnapPos(float val)
{
int rem = val % 32;
int desiredVal = val - rem;
if (rem >= 16)
desiredVal += 32;
return Mathf.Lerp(val, desiredVal, lerpSpeed * Time.deltaTime);
}
I made u a little function
if you give it a float of your position, it will return a next position you should be for that axis
transform.position += (Vector3)(direction * maxSpeed * Time.deltaTime);
if (verticalMove)
{
// Snap horizontally
transform.position += new Vector3(NextSnapPos(transform.position.x), 0);
}
else if (horizontalMove)
{
// Snap vertically
transform.position += new Vector3(0, NextSnapPos(transform.position.y));
}
@balmy radish and then something like this maybe
I havn't tested it but you can play around and you need to create the variables for horizontalMove and verticalMove (they are bools) and if you move horizontally you need to set horizontal move true for example
wait lemme try it ^^
and also set a lerpSpeed, if it works, then good, but I didnt make it for that purpose, this should just be an idea how you could solve a problem like this
yes thx verymuch it is not working rightnow but i got the idea and iwill change it like that ^^
thx verymuch again ^^
do you understand the logic though?
Yes iam just trying to understand why the player if flying with 15555000000 speed Xd
LOL
make lerp speed small then
smaller than 0.005`=? XD
wait
XD
you want 32 pixels right?
i said the Sprit is 32
you want to snap how many units
ohhh wait then
sure
Does IL2CPP produce faster code than Mono? Should you use IL2CPP everytime when producing a release build?
in my experience on desktop platforms, il2cpp produces faster code. on hdrp projects, which have greater cpu needs than urp, i've seen frametime improvements of about 5%
so il2cpps never slower?
are there any downsides to using il2cpp beside longer compile times
if it turns out to be slower, usually there is some other bug
if you author a moddable game, it is much easier to do it targeting mono than il2cpp
i looked up il2cpp and it looks like unity games compiled with it are very easy to mod with decompilation tools, should i care about that?
thanks man
Can someone help me understand how machine ends up as null? I copy and pasted the file path of my prefab so I'm incredibly frustrated.
the Prefab folder needs to be in a Resources folder in order to use Resources.Load()
you shouldn't use Resources.Load. simply drag and drop it directly into the slot on your behavior. also, there are spaces in your path. you are on the start of a long journey!
^ yeah sorry i didnt actually look fully at your code, i agree with doctorpangloss. Referencing a prefab in the inspector is a lot better than using Resources.Load
you've already made it a [SerializedField] too
What should I do if I am going to be changing the prfab a lot though?
wdym changing
I change it based on player input then instantiate a new Game Object and delete the old one
its a building system
Should I just have like ten GameObject variables and assign them in the inspector?
how is the player choosing the input?
no you should have one array variable and assign it in the inspector
That shouldn't affect it but they use the number keys
oh thats a fair point lol
number key to array index then?
Yeah that's what ill do that's a good idea
Just out of curiosity, how would you do it the "hard way"?
Like if I wanted to grab a prefab with code instead of using the inspector?
i probably would never use Resources.Load, and just have some sort of storage system of prefabs in a singleton Scriptable object
but with what you were doing originally you could use Resources.LoadAll from a folder and then make the array but you'd need to have a script on those prefabs to determine the order so your number keys don't change if you add a new prefab
the spaces in your prefab path mean you really, really should not be using Resources.Load
so it's not super clear to me why you want to do things this way
The spaces are straight from copying it I don't know why they are there and now worries I figured out a solution
I would personally use addressables if I wanted to grab things without the inspector
well you should maybe start with #๐ปโcode-beginner and some tutorials, i like ray wenderlich's because they're nicely written
thank you for telling me that ๐
Hey everyone,
Recently I uploaded my android game to Google Play Store. I have integrated Unity Analytics/DevOps. In the DevOps panel I see that 5 users out of 300 ecountered an error:
Managed Stack Trace:
UnityEngine.SceneManagement.SceneManager.UnloadSceneAsyncInternal (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.UnloadSceneOptions options) (at <00000000000000000000000000000000>:0)
SceneLoader+<LoadCoroutine>d__10.MoveNext () (at <00000000000000000000000000000000>:0)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <00000000000000000000000000000000>:0)```
I'm unable to reproduce this manually on any of the devices that I own. Here's the code that I use for loading/unloading scenes:
```private IEnumerator LoadCoroutine(string sceneName)
{
_loading = true;
var scene = SceneManager.GetActiveScene();
// load transition scene
yield return SceneManager.LoadSceneAsync(LoaderSceneName, LoadSceneMode.Additive);
SceneManager.SetActiveScene(SceneManager.GetSceneByName(LoaderSceneName));
yield return null;
// unload original scene
yield return SceneManager.UnloadSceneAsync(scene);
yield return null;
// load new scene
yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
SceneManager.SetActiveScene(SceneManager.GetSceneByName(sceneName));
yield return null;
// unload transition scene
yield return SceneManager.UnloadSceneAsync(LoaderSceneName);
_loading = false;
Am I doing something wrong? Why would this occur only on 5 out of 300 devices? I'd appreciate any help.
the most likely explanation is an application bug. i don't think there is enough information in this error to definitively say
ideally you would not use scenes
why not? aren't scenes one of the most basic structures in unity?
you could, for whatever reason, have an improper (unintended) state generated via your code that could cause this function you sent to error
i'm not sure if they provide value for you over prefabs. the issue you're experiencing is one of many anecdotes and problems
related to scenes, and the workarounds needed to do basic things like having an object that persists across scenes
anyway it's everyone's prerogative. i give this advice all the time, and i'm always right about it, in the specific context i give it
i don't know if your game needs scenes
you can probably store all the content in one scene
and use prefabs for your levels
you do not call Resources.UnloadUnusedAssets are you? if you're not calling it, you're not saving any resources, which is what you're about to say as to why you need scenes
even though that interacts correctly with destroying game objects for any reason, not just game objects that are destroyed by unloading scenes
a little silly to recommend such an architectural change when the game is already on the google play store
I don't ever call UnloadUnusedAssets
5 out of 300 users that can be observed
Am I doing something wrong?
if you can use just 1 scene, and remove all the complex code you have for deawling with transitioning between scenes, and instead use prefabs and simply
SetActive(true) on thigns that should be visible, SetActive(false) on things that should not be visible, which literally replaces 99% of SceneManager use cases
then in a sense you are doing something wrong. there's nothing wrong with your code here
is it possible that you could be starting this coroutine in quick succession? i.e. before the previous one finished?
Why would this occur only on 5 out of 300 devices?
given how hard it is to figure this error out, there is probably an application bug relating to multiple game objects with dontdestroyonload or similar techniques to persist between scenes, interacting unusually, in a situation that is hard to reproduce / QA
i don't know, it would probably take me about 2 hours to remove scenes
in a codebase i've never seen
2 hours is nothing
drag and dropping all the content of the scenes into prefabs, creating a new Game scene
removing all the weird code
then using SetActive
it's not bad
i don't know anything about the game
but hey, you've probably spent more than 2 hours dealing with this bug
or will
so it's your call
your game
Yeah, it is his, so chill out on the random controversial suggestions
I don't think so, I block all of the input when scenes are changing and user shouldn't be able to invoke another loading but I'll double check, thanks
do you see what i mean?
look at how much stuff you have to do
blocking input, toggling loading... for what exactly?
DontDestroyOnLoad?
don't you see
you don't need any of this if you just use prefabs to organize instead of scenes
this is obviously organizational
you can organize your stuff into prefabs
all of this effort put into a suggestion he doesn't need
it is basically thes ame experience in editor
how would switching to prefabs omit the need to blocking the input?
because SetActive(true) or Instantiate will Just Happen
you already do it all the time
you already use prefabs
but Set active/Instantiate blocks main thread when it needs to load something
Just store your entire game levels in prefabs and freeze your application while you enable / disable them ๐ค
your application will freeze loading scenes too
"async" doesn't mean no freezing
and besides, if you have everything instantiated - i always pre-pool, put a prefab reference directly into the scene, etc - there will be less freezing compared to loading a scene
@warm yarrow anyway you won't fix this problem, trust me
it's extremely obscure
Hmm, well I would consider seeing a moving load screen with an animated load bar to not be "frozen", but I guess we all see things differently
1.6% error rate... you are going to have to play your game for hours upon hours to reproduce this
@polar marten I appreciate your advice but you are suggesting a solution that interferes with the way Unity is designed
i am suggesting to use prefabs
which is another way unity is designed
i'm not suggesting any interference
i'm suggesting a solution that interferes with how you like to organize and think, which is, "i have a lobby scene" "i have a game scene"
but unity doesn't care
and i'm suggesting you just have a lobby prefab
how would I bake lightning in the prefab?
i think there are a ton of google results for this
there might be, but you said you could convert any Scenes system into prefabs system
that's correct
i would probably just drop the prefabs in and bake them into the scene
Yeah, you can bake lighting into prefabs
once
and then move on with life
because that would take like 5 minutes
then move them out
oh, I didin't know that
love your optimism for baking times
well, i would bake my assets in a graphics application
Hah yeah then that makes sense
is sort of the right answer
none of us can do anything about how crappy unity's lighting is
anyway I feel like this conversation is drifting away
Has been for a long time.
the error message is telling you something that makes literally no sense
which i hope has illuminated for you how utterly brittle and stupid SceneManager is
it is so bafflingly stupid and frustrating that you could wind up in a situation where a super straightforward piece of code causes crashes
you can probably reason about baking, but this
this is a disaster
we can all speculate about random shit
that can happen during the execution of this coroutine
but i'm sure you've already done that
so people who have never seen yoru game's codebase or even what scenes are being loaded aren't going to have extra insights
the underlying problem is that Scenes are bad
just consider it
1.6% that you observe. it's possible that many, many users will eventually see this bug and drop out
okay, I'll keep that in mind, but I'm sure most of the unity developers use scenes
which is why i find crashes like these so frustrating
I have used scenes with no issues for nearly all my projects, albeit I generate and populate them at runtime. I do still use pre-populated scenes for things like levels and have never encountered issues.
and they find a way to do that without issues
does unity have a situation where you end up writing everything yourself
like 1.6% error rate isn't small - people who stop playing stop generating data, so it's possible to observe 1.6% reports for an error that, eventually, 100% of users experience
I've never had issues with Scenes
like a windows C/C++ runtime kinda deal
they write a lot of code to work around using scenes
I'm not sure I believe most Unity developers have not run into issues with Scenes
like DontDestroyOnLoad, "brain" scenes, etc. etc.
most unity developers ship 0 games
and you have, you have a game that's live with a finger pointing right at scenes!
i mean that's what the error message is saying. "this seemingly straightforward and obvious pattern, i'm just going to decide it doesn't work for you, because scenes"
one of the requirements i have for people who use an sdk i develop is that they have only one scene lol
because it's SUCH a common problem
and 100% of the games that use this sdk will be shipped, so there's no point in letting people "organize" or whatever
they can organize using prefabs
most of the time people are rewriting stuff in a negative return-on-investment sort of way. i see this most commonly with Amplify Shader Editor users
that said, the workflow i'm describing is literally dragging and dropping prefabs into a scene, and then using SetActive wherever you would do scene loading. that's it, that's the whole idea
you get to eliminate a ton of other code by doing things this way, so it is definitely ROI positive
I think that would work for a small game that doesn't need complex memory management
you can Destroy then call Resources.UnloadUnusedAssets()
the number of lines of code between this method i'm suggesting and scenes would not change, in order to do "memory management"
then i suppose you'll have to instantiate
all things you've done a million times before
and that would freeze the application unless I used Resources.LoadAsync or asset bundles
that said, i think you should try to not juggle the memory like this unless you really have to. for mobile devices, you will get higher yield compressing your textures, mesh combining with an asset, atlasing, etc. than futzing about with all of this
loading a scene asynchronously also freezes the application. surely you have observed this. it's not what async loading does
async doesn't mean not freezing
if you want to throw up a loading thing
you can do it. setactive on a loading UGUI panel
the progress bar will freeze, but it does that anyway, in both scenarios
hello is there a way to change FixedTimeStep from script?
hmm you can get animated progress bar with using load async so there's no way it completly freezes the application
the key difference between what i'm describing and what you're describing with SceneManager is bugs
you know i'm talking about stuff that doesn't cause bugs!
Time.fixedDeltaTime = yourValue;
Can you guys move this into a thread in case others have questions?
if you do not observe "freezing" with async loading, you won't observe "freezing" with setactive on a gameobject in your scene. however, as you know, you DO see freezing with SetActive on a game object in certain circumstances, and that same freezing IS occurring when loading a new scene with that same game object active for the first time. loadasync's superpower is dealing with assets that are on disk and turning them into something that the game engine can use, which i agree is valuable and can reduce freezing
but here's the thing: a user will literally never complain about stuttering during a loading bar on screen - the amount of total time they're waiting will be the same regardless of whether or not you use scenes or prefabs or anything - whereas they will stop playing if your game crashes
@warm yarrow so what i am basically saying is: scenes are useful but they are full of bugs.
they're full of bugs that make people quit
it's your prerogative, it's your game
I appreciate your feedback
Hello fellas, im currently losing my sanity trying to make a "Spell inventory" or something similar to World of warcrafts spell system. I want to be able to drag and drop available spells onto a hotbar and use the spells from there. But i cannot find any good tutorials for this. Does anyone have a good tutorial for this? or is someone willing to be my teacher and get paid?
@radiant notch did u still need help?
Can i private msg u?
ofc
i am trying to get the tile coordinates of a tile clicked, using the built in Unity tilemaps, however for some reason i am always getting the same position:
Vector3Int tilemapPos = tilemap.WorldToCell(Camera.main.ScreenToWorldPoint(Input.mousePosition)); Debug.Log(tilemapPos); // always returns (-1, 1, 0)
how do I reset the model after an animation?
I call
player.animator.Play("DeathAnimation", -1, 0f);
then the body has the effect of laying on the floor, then after 5-6 seconds I want to "respawn" the player but he's stuck in the lying down position
how big is the tilemap board
debug the raycast
use transition states
something like 10 x 10 to test, nothing crazy
i might have figfured it out
did you figure it out ?
does anyone know how to change a value over time while being able to modify It? I have a function that that when called, will lerp a value over to 3 over 1 second. The only problem is if I call this function again say .5 seconds before the other ends the values get messed up. I need to be able to call the function again so if you call it half a second after the first it adds to the other value so it than takes 1.5 seconds to lerp to 6 can anyone help?
Just use MoveTowards
float current = 0;
float target = 0;
float speed = 1;
void Update() {
current = Mathf.MoveTowards(current, target, speed * Time.deltaTime);
}
void SetTarget(float newTarget) {
target = newTarget;
}```
Ok will try this thanks a bunch! I appreciate it
I've included some code of mine (that doesn't work) but it's just there as a reference.
Let's say I have three scripts. PanelsManager, PanelsParent, and ItemPanel.
PanelsParent serves as a parent to instantiated ItemPanel prefabs.
ItemPanel prefabs have the ItemPanel script, which takes information about Items in the player inventory and displays them in the ItemPanel.
PanelsManager takes care of adding and removing ItemPanels as children to the PanelsParent Transform.
I have no problem instantiating one panel for each Item in the players inventory.
However, what I want to do, is only display one panel per item type. For example, if I have three swords in my inventory, and two shields, two panels will be instantiated, one panel for a sword, and one panel for a shield.
My script isn't working for this. It will display the first item, but after adding a second, no panels will display at all.
Has anyone had a similar problem using the Unity Localization Package? Every time I save I get this error:
Failed to find entry-points:
System.Exception: Unexpected exception while collecting types in assembly `Unity.Localization.Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null` ---> Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Unity.Localization.ThirdParty.Editor, Version=12.0.0.0, Culture=neutral, PublicKeyToken=null'
at Mono.Cecil.BaseAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference name, Mono.Cecil.ReaderParameters parameters) [0x00105] in <ebb9e4250ed24cbfa42055e3532ef311>:0
at zzzUnity.Burst.CodeGen.AssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference name) [0x00039] in <a2dd15248a25411e914af2a2c82fb63f>:0
at Burst.Compiler.IL.AssemblyLoader.Resolve (Mono.Cecil.AssemblyNameReference name) [0x00079] in <a2dd15248a25411e914af2a2c82fb63f>:0
at Mono.Cecil.MetadataResolver.Resolve (Mono.Cecil.TypeReference type) [0x00038] in <ebb9e4250ed24cbfa42055e3532ef311>:0
at Mono.Cecil.ModuleDefinition.Resolve (Mono.Cecil.TypeReference type) [0x00006] in <ebb9e4250ed24cbfa42055e3532ef311>:0
at Mono.Cecil.TypeReference.Resolve () [0x00006] in <ebb9e4250ed24cbfa42055e3532ef311>:0
at Burst.Compiler.IL.Server.EntryPointMethodFinder.CollectGenericTypeInstances (Mono.Cecil.TypeReference type, System.Collections.Generic.List`1[T] types
...
I searched in some forums, but I didn't find the solution. (Full stack-trace: https://gdl.space/sigopoqoza.coffeescript)
A little confused, the documentation says LineRenderer.GetPositions should be given an out keyword parameter but it's returning an error, what's going on?
does this happen in all yoiur scenes?
it looks like your project is in some jeopardy. do you use source control?
do what your editor is saying
also, your editor is configured right?
don't forget to initialize your array
How so?
almost forgot, making progress now
also what version of unity are you using? because older versions did not have that as an out parameter, just as a regular parameter
2021.3
See what your IDE says the method signature is
the docs might be out of date or just wrong
According to mine it's just a regular parameter, no out
out wouldn't really be needed for an array parameter anyway, since arrays are reference types. I think the docs are just in error
Doesn't exist?
you're mousing over positions which is your array
mouse over GetPositions
yes, do what the editor is saying
you are looking at the docs for an older version of unity than you are using
Nah the docs are actually just wrong
really?
Yeah. At least for 2022.2 they are.
Docs for 2022.2 say out but Rider says no out.
yep, just checked 2023 and there's no out param but the docs say there is
I reported the doc page as incorrect, not that this has ever yielded any results in recent memory ๐
well if you want to send some reports directly to the trash you can do that right from the comfort of your desktop
Funnily enough I'm reading 1984 right now and there's a lot of mention of "memory holes"
It seems like this is a memory hole ๐
what am i doing wrong? i confirmed the two objects are in layers "Bullet" and "DeadPlayer", yet they are still colliding?
are you looking at the correct physics settings? if you're in 2d make sure you're modifying the matrix in the Physics2D settings
also not a code question
ok ty let me see
thank you! i think that's it (it wasn't set in 2D)
sorry i didn't know
it is a newly created 2D project (URP) and has only the default scene. I'm using git.
No motion is being produced. Anyone know why? The idea is curved movement.
debug values
Hmm why are you updating/populating _startPosition inside the loop?
no, i didn't
np, was just wondering if i was missing something obvious
maybe it's the Z position
did you try to just set it to 0 since that seems to be your Z
For if the end position moves it will continue towards new position from current position
But what is _startPosition when the coroutine starts?
okay, thank you
transform.position
Hm so all the time values are coming out correctly... Is there something wrong with the AnimationCurve?
using UnityEngine;
public class MapRules : MonoBehaviour {
// Set up in inspector on each map if required
[SerializeField] private bool _canTP;
[SerializeField] private bool _canAttack;
...
private static int _mapRules; // Up to 32 rules (1 << 31)
public static bool canTP {
get => (_mapRules & (1 << 0)) == 1;
private set => _mapRules = value ? _mapRules | (1 << 0) : _mapRules & ~(1 << 0);
}
public static bool canAttack {
get => (_mapRules & (1 << 1)) == 1;
private set => _mapRules = value ? _mapRules | (1 << 1) : _mapRules & ~(1 << 1);
}
...
private void Awake() {
UpdateRules();
}
private void UpdateRules() {
canTP = _canTP;
canAttack = _canAttack;
...
}
}
Yo, I've been thinking of a way to set up different rules on each map of my game and came up with such an idea, but I don't really yet fully understand what properties are in C#
Is my understanding here, as to how should I use them, correct or should I do it in some other way instead?
I am having such a weird brain blockage at the moment, and embarrassingly it's something I always seem to have a problem with. lol.
Could someone point me in the right direction on this one please?
I have a ray shooting out from the camera that hits an object, and I'm trying to get the object to move to the player, but for the life of me I can't figure out how.
Here's the code, I know that it's massively messy, but atm I just want to get it to work. lol.
bare with me.......bloody character limit. lol.
!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.
Ah didn't know about that command. lol.
you could use enum flags, make it more readable?
I just can't get animation curves to do anything for me. There are tutorials, but none of them have to do with moving an object along a curved path
Even asked chatgpt, it also doesn't know what's wrong, lel
[Flags]
public enum MapRules
{
None = 0,
CanTP = 1 << 0,
CanAttack = 1 << 1
}
public static bool CanTP {
get => (_mapRules & MapRules.CanTP) == 1;
private set => _mapRules = value ? _mapRules | MapRules.CanTP : _mapRules & ~MapRules.CanTP;
}
Ah, very true, thanks
I'll do that
But besides that it's ok, right?
but yeah properties i think are ok for that
some people might say only have those be getters and use a function to set instead
public static bool CanTP => (_mapRules & MapRules.CanTP) == 1;
public void SetTpState(bool state)
{
_mapRules = state ? _mapRules | MapRules.CanTP : _mapRules & ~MapRules.CanTP;
}
Are you sure you are starting the coroutine with StartCoroutine
The fact that you say "no motion" makes me wonder if it runs at all
I see
Basically what's happening is the object immediately teleports right to the end point, or very close to the end point. Then doesn't do anything else. And it's being caused by the coroutine because when I comment it out, it just sits at the start position
So are you changing startPosition before the coroutine starts?
Only thing I can think of is the curve.Evaluate is being weird
no. I just meant it stays wherever it was spawned
Can you paste your code here so its easier to refer to
In your current while loop, you are updating the gameObject's position before you have changed _startPosition
Isn't if(_endPosition != transform.position)
supposed to be if(_endPosition != targetTransform.position)?
K, I have movement now. Yay. The movement is very bizarre and not what I predicted, but still
with [Flags] can't i just make the properties have only get, make a [SerializeField] private MapFlags mapEnumFlags and set the rules with mapRules = (int)mapEnumFlags ?
yeah, if you only need to set in the inspector
how can i make a freekick system for unity
If you wanted to use an animationCurve to move an object in an arc, wouldn't you do this?
transform.position = new Vector3(_startPosition.x + xCurve.Evaluate(elapsedTime), _startPosition.y + yCurve.Evaluate(elapsedTime), 0);
like soccer freekicks?
3D or 2D
myriad of ways to do it
3D soccer freekick,
and thanks i needed this
lol, don't use that. I'm trying to use it and I can't get it to work
this wont work well for you because they are set curves
you probably want physics + forces
yeah
Idk, football game using set curves could be pretty fun
you can charge up your shot and kick it, idk anything about your setu tho
๐
i dont need a very advanced system, but a ball going towards the target is enough for me for now, the most important part is curve.
Imagine a pause-and-play football game where you have to choose the right curve to kick the ball in, like a strategy game
what kinda view like this ?
my picasso skills
but um, like bar to charge shot ?
shoot infront of goal?
nope, wait
Good luck, curves are apparently the hardest thing in unity
this camera position is same with my project
it is no harder to implement a curve than a straight line
show me how, lol
this isn't very difficult
google C# bezier curve algorithm
break it down to smaller tasks you need to get done @cedar pivot
you have a very open ended question
too many abstact ideas floating , we need to know specifically what mechanic your first working on and need help with
K I'll try to do this instead of trying to use AnimationCurve. But I find it hard to believe something is as easy as a straight line when you have to do stuff involving
so, it makes more sense to improve the system and ask you where I got stuck while developing it.
random question, how do we feel about the built-in unity character controller component
exactly
you do not need to understand the underlying math to be able to implement the algorithm
is pretty good and can be customized easily
not until something goes wrong and you have no clue how to fix it lol
Bezier curve is just a few lerps
fine, I'll do math witchcraft
But im not sure why this wouldnt work. Check the scale of your curve's keys, and that elapsedTime is a correct value
yeah, it seems super easy to use
Did you even bother to google?
https://stackoverflow.com/questions/13940983/how-to-draw-bezier-curve-by-several-points
this give you all the code you need
Ah, so you need to dynamically change the curve's scale?
No. Just look at the keyframes in the curve. And check that the value is something sensible like 1 (not 0.001)
And the time value of the keyframes too.
here's an interesting question, if you had to have a collection of default components, almost like a template for a 3D game, what would you use? i'd probably use cinemachine, character controller, and then i guess fill in the gaps with stuff like healthbar/resourcebar scripts that ive made a million times
@hard sparrow
Another resource for beziers, with nice visualizations:
https://www.gamedeveloper.com/business/how-to-work-with-bezier-curve-in-games-with-unity
[Flags] private enum MapFlags {
None = 0,
CanTP = 1 << 0,
CanAttack = 1 << 1,
CanOpenBook = 1 << 2,
CanUsePotions = 1 << 3,
ResetEffectsOnLoad = 1 << 4
}
[SerializeField] private MapFlags _mapFlags;
private static int _mapRules; // Up to 32 rules (1 << 31)
public static bool canTP => (_mapRules & (int)MapFlags.CanTP) == 1;
public static bool canAttack => (_mapRules & (int)MapFlags.CanAttack) == 1;
public static bool canOpenBook => (_mapRules & (int)MapFlags.CanOpenBook) == 1;
public static bool canUsePotions => (_mapRules & (int)MapFlags.CanUsePotions) == 1;
public static bool resetEffectsOnLoad => (_mapRules & (int)MapFlags.ResetEffectsOnLoad) == 1;
private void Awake() {
_mapRules = (int)_mapFlags;
}
I am kinda confused..
I set up CanTP, CanAttack and CanOpenBook in the inspector, when debuging _mapRules, it's correctly showing 7 (1+2+4, first three flags) but when debugging all the properties, only canTP shows true while the rest is false.
I must be blind, can someone show me what am I doing wrong here?
oh..
I spotted it, nwm.
shouldn't be ==1 everywhere
!=0
was about to say that
ah i think it might be != 0
though i'm not the best with flags
also, ive never seen that [Flags] property before
Yeah, it should be that..
and i usually just cheap out and use _mapRules.HasFlag(MapFlags.CanTP); (if you make _mapRules into MapFlags type)
but it is worse performance than doing it manually
Me neither, learned about it just today, quite handy
what does it do?
- in inspector
though i gave the bit shift example
absolutely wild, cant believe ive been doing it manually this whole time
basically multi bool
how can I make my volume setting save through scenes?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SoundManager : MonoBehaviour
{
public static SoundManager Instance;
[SerializeField] private AudioSource musicSource, effectsSource;
private void Awake()
{
if (Instance)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
public void PlaySound(AudioClip clip)
{
effectsSource.PlayOneShot(clip);
}
public void ChangeMasterVolume(float volume)
{
AudioListener.volume = volume;
}
}
currently, I have a sound manager like this and its in the main menu scene, but when loading into another scene it seems to reset the audio back to 100%
try moving the ChangeMasterVolume(0.1f); to above the DontDestroyOnLoad(gameObject);
no, ignore that part
the function "ChangeMasterVolume"
gets called by another script anyways
that was just a test sorry i forgot to remove that from the code
you could use the PlayerPrefs system
void SavePrefs(float masterVolume,...){
PlayerPrefs.SetFloat("masterVolume",masterVolume);
//best practice to prevent dataloss is to store floats as a string, this avoids floating point error
PlayerPrefs.SetString("masterVolume",string.Parse(masterVolume));
//believe this saves to disc, not sure if needed or not
PlayerPrefs.Save();
}```
i would also recommend looking into the unity mixer if you haven't, that could help you create even more options for volume/mixing
Help needed. For some reason, when I interact with my soil when it's SoilState.Harvestable nothing happens. SoilState.Overgrown functions as intended but I can't even get the Debug.Log to show for SoilState.Harvestable. I've tried removing the switch and replacing it with if statements, I've tried just having the code say if (currentSoilState == SoilState.Harvestable) { Debug.Log("Working") } but I get nothing. I can verify that the soil's state is set to harvestable because the inspector clearly shows it.
are you changing it anywhere in code?
how do you set the states ?
Setting them from here.
where are u calling UpgradeGrowth
did you debug isGrowing ?
wait, sorry is "Nothing to cut." being logged?
Hello how can I create a 3d tilemap?
I tried creating a lot of square planes using 2 for loops but it kills my CPU and RAM. Is there an optimized way to create it?
I want to make something like this
put them in a coroutine
No
how are you calling SickleSoil()? as that doesnt seem to be working if you are not getting any log
do you mean you "lock up" when you generate
or you lag once it's generated
it lags in runtime, after being generated
this is my map, it's composed of a lot of squares
every square is a tile
eh you'd probably want Dots or chunks then
To clarify, "Nothing to cut" is logged when the soil is activated on any other state other than Overgrown and Harvestable. If the currentSoilState is SoilState.Overgrown the code functions as intended. The code for SoilState.Harvestable is exclusively not working.
it doesn't seem too big tho
what are those?
it's 100x100
well this is wrong
To clarify, "Nothing to cut" is logged when the soil is activated on any other state other than Overgrown and Harvestable.
you are using break; in the switch so "Nothing to cut" should always be logged even on those states.
so you must not be calling SickleSoil correctly, trace it backwards
maybe it's just your pc then, check it with the Profiler
if SickleSoil() is not being called, why does the code for case SoilState.Overgrown execute?
unless you are throwing due to an error it should log "Nothing to cut" everytime you call SickleSoil no matter what happens in the switch
Okay, "nothing to cut." shows for the Overgrowth as well. That was my mistake.
ill try
It's only Harvestable it doesn't show for.
well that means that some check is blocking SickleSoil running when it has the Harvestable state
i can't help you much more without seeing the full code
!code, you can paste it to one of those sites if you need further help
๐ 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.
This is helpful, I will look into this
hey, i've got a strange issue, im using omnisharp with VSCode and for some reason it doesnt know what cinemachine is. This compiles though
regenerate project files and restart vs code
just thought to try that, its working now
VSCode being VSCode
what do you mean by 3d tilemap?
Can anyone identify why my code is throwing an error on Line 113?
https://gdl.space/lidiqatabe.cs
This script was functioning as intended, but I moved the script to another GameObject, and since then, it has been throwing a NullReferenceException on Line 113 which seems to indicate that "selectedSeedListPanel" is equal to null.
What I don't understand is why moving it to another GameObject would cause the issue, as everything is still being properly instantiated, and everything else is functioning correctly.
Moving it back to its original GameObject resolves the issue, but I need to move it as it was not an appropriate place to have the script.
if (ci is SoilObject soil)
{
soil.PlantSeed(selectedSeedListPanel.seedContained);
}
You can do this fyi
is not as
oh yeah is not as sorry
it can't be that it's not reaching the seedContained variable in selectedSeedListPanel, because the instantiated panel contains it, so it must be that selectedSeedListPanel is equal to null. However, when one of the panels is instantiated, the class subscribes to that panel's callback, so that when it's clicked, the selectedSeedListPanel is updated to that panel.
Moving the script shouldn't change that, and the fact that I'm getting the error means that the callback is functioning...
are you certain that the updateSelectedSeedPanelCallback is being invoked with a non-null value passed as a parameter?
This is the only place it is being invoked.
0 references
so where are you calling that method from?
When clicking this button.
The script (SeedListDisplay) was originally attached to UI_SeedPrompt and I get no errors when it is attached to this GameObject. The problem is non-existent.
However, I re-attached it to UI Manager instead, as UI_SeedPrompt is not always active.
Since attaching it to UI Manager, this is when the NullReferenceException started appearing.
i'd place some breakpoints and make sure that the methods are being executed in the order you are expecting them to be
Well, clicking a Frame executes the callback method. I can't see any reason why the seedListPanel shouldn't be updated with the rest of the code. It's not being cleared anywhere else.
something like this
How are you creating this?
I'm interested in implementing sprite generator or something
Not sure what to call it but you can see that each can be connected by a that brown part(root)
I'm interested to know if there's an interesting/fast method to implement it without do it statically
Like a mesh generator or a spline maybe and if it's in the case of spline, would it be easy to implement(Within a short duration of time)?
The shape the linerenderer I have is rendering is a little off kilter, but all the points are whole numbers. What's going on here?
This is the exact same idea we had for our jam at first xD
haha, not a big fan of creating meshes? :d
Not in the slightest lel
I'm trying to make it so when the player kills an enemy, after 3 seconds the enemy will sink into the ground but the ground is interfering with the enemy even though the enemy's collider is disabled. And in the Scene when the in playing, I am able to move the Enemy's position through the ground manually with no problems. Any idea why? https://streamable.com/a950eu
Vector3 targetPos = new Vector3(transform.position.x, transform.position.y - 3, transform.position.z);
transform.position = Vector3.Lerp(new Vector3(transform.position.x, deathPos.y, transform.position.z), targetPos, 0.1f * Time.deltaTime);
if (transform.position == targetPos) Destroy(gameObject);```
It's so weird. selectedSeedListPanel is successfully assigned a value. It's not changed from anywhere else. When it is called it's null - but only when the script is on my UI Manager class, and not the parent class of the tree that instantiates my panels.
maybe remove ridgidbody as well
Now I can even see in the inspector that it is assigned a value?? Why would Debug.Log() show it as being null when the inspector clearly shows it as an assigned value?
It doesn't have a rigidbody
I think you got something wrong about the lerp function
Which part of it? I followed the documentation
if(getsKilled)
{
int steps = 20;
Vector3 pos = transform.position;
Vector3 goal = new Vector3(pos.x,pos.y-3,pos.z);
Vector3 interval = (goal-pos)/steps;
getsKilled =false;
}
if(isdying)
{
steps--;
transform.position+=interval;
if(steps==0)
{
isdying =false;
GameObject.Destroy(gameObject);
}
}
//Try this I know this can be simplified but having more readable code is worth it when you have an error that you can t find
Why aren't you using lerp? ๐ค
If you look at the video, it really looks like the enemy is colliding with the ground
it does indeed
but what seems of about your code is that you don t make a difference between the enemy having died and being dead
I already did that, I just didn't send that code
I just sent the relevant code
idk I'd be great if you tried mine and if it doesn t work you can still use urs
Actually I changed the negative to a positive to see if it will float into the air and it does the same thing so its definitely not an issue with colliders.
I will try your code but I've always used lerp with no issue.
the thing I wrote is just like lerp I think
anyone knows what that does?
@simple mountain It works, thanks!
that thing is chewing 6ms
Just experimenting randomly with some things. Would this be a good thing to do? Only thing vs complains about is Cannot initialize type 'float' with a collection initializer because it does not implement 'System.Collections.IEnumerable' (Which sadly I need a dll for it) but then again, is this a valid way of doing it?
Edit: maybe it's not a dll? Potential fixes aint giving any useful fixes though
float[] deltas =
{
new float { firer.x - target.x },
new float { firer.y - target.y },
new float { firer.z - target.z }
};```
firer and target are just vector3 parameters of the method
wait
nvm still dont know
float[] deltas = { firer.x - target.x, firer.y - target.y, firer.z - target.z };
but I wouldn't do it like that, why allocate an array?
Vector3 deltas = firer - target;
You can still iterate through deltas if you need to do whatever it is you're doing with deltas
only thing i wanted to do is sort which delta had the highest value, so i thought OrderBy would do the trick
hence why i wanted to make an array
float maxDelta = Mathf.Max(firer.x - target.x, firer.y - target.y, firer.z - target.z);
you can slap in abs in there if you're looking only at magnitude
technically the optimal solution is two maxes imo, since the 3 parameter version allocates an array which should be avoided in a hot code path which it sounds like this will be
Hello!, im really new to unity, is there a way to code in lua or is it only just c#
No lua
Ah okay
How do I make a script that increments a value by one when a gameobject is set to active?
Hello is there a way to add a scriptableObject into a non-Monobehavior? (Without adding it by constructor)
broadcast an event when you use OnEnable
Look at this video: https://www.youtube.com/watch?v=v7yyZZjF1z4 it might not fully be what you want but should be a good starting point
Learn how to create procedurally generated caverns/dungeons for your games using cellular automata and marching squares.
Source code:
https://github.com/SebLague/Procedural-Cave-Generation
Follow me on twitter @SebastianLague
Support my videos on Patreon: http://bit.ly/sebPatreon
hi, i'm trying to do
float waveHeight = WaveManagerGerstner.instance.GetWaveHeight(transform.position);
but it's mad that i'm feeding it the transform.position. it says: There is no argument given that corresponds to the required parameter '_y' of 'WaveManagerGerstner.GetWaveHeight(float, float, float)'
the getwaveheight function in question is:
` public Vector3 GetWaveHeight(float _x, float _y, float _z)
{
Vector3 gridPoint = new Vector3(0, 0, 0); //vertexData.vertex.xyz;
Vector3 tangent = new Vector3(1, 0, 0);
Vector3 binormal = new Vector3(0, 0, 1);
Vector3 p = new Vector3(_x, _y, _z);
Vector3 currentPosition = GetWaveAddition(p, gridPoint, ref tangent, ref binormal);
Vector3 normal = Vector3.Normalize(Vector3.Cross(binormal, tangent));
Vector3 displacement = GetWaterDisplacement(_x, _y, _z);
for (int i = 0; i < 3; i++)
{
Vector3 diff = new Vector3(_x - currentPosition.x, 0, _z - currentPosition.z);
currentPosition = GetWaveAddition(diff, p, ref tangent, ref binormal);
}
return currentPosition;
}`
i'm quite confused; why is it not happy with what i am feeding getwaveheight function?
var pos = transform.position;
float waveHeight = WaveManagerGerstner.instance.GetWaveHeight(pos.x, pos.y, pos.z);
^ it wants the x,y,z properties of the position vector, not full vector
Oh duh! Thank you.
@hexed pecan @knotty sun I implemented bezier curves and it works perfectly and is way more flexible. Thanks for the help.
(turns out doing your own bezier curves is way simpler than trying to finagle unity AnimationCurve)
How good is unity's navigation and pathfinding?
depends on your usecase
if you have navmesh based navigation for 3d its fine
or as long as you can bake the navmesh and do not need to make large changes to it at runtime
ahh okay
i have used it for some projects, and i have just implemented my own pathfinding system on others. depends on the needs at the time
ah what are the use cases where you have to implement your own pathfinding sys
i needed grid based and i needed to modify it at runtime
I keep getting broadcast message has no receiver. you know how to fix that
Its a* on 3d nav mesh agent
Ahh okay
JsonUtility isn't super clear about what happens when things go wrong. If it attempts to deserialize data that is corrupted will it throw an exception or just return null? https://docs.unity3d.com/2020.2/Documentation/ScriptReference/JsonUtility.FromJson.html
Hold up... What are you trying to do here? This will generate garbage collection.
Figured the issue out, scrapped the whole new float thing and only left the floats in the brackets
Idk why i did that to begin with
You're using Send Messages?
show code
hey, i have this variable called speed in a base class and in the child im trying to do animator.SetFloat("speed", Mathf.Abs(direction)); but it cant find the float speed
i couldnt find anything on the docs
the speed in animator.SetFloat has nothing to do with your base class
its setup in the animator its self in parameters
ahh, so this is because i havent set up anything in my animationer yet
yeah the various animator.SetX methods are for setting paramaters on your animator controller
ahh, so i should rename it to like animation_speed right?
the string you give it depends on what you have setup in your animator controllers parameters
the docs give a example of usage
I am having an issue with Pathfinding. The default rotation for my character models is (-90,0,0) however this happens when running the following script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCWalk : MonoBehaviour
{
public float updateFrequency = 2.0f; // Time in seconds between updates
public float speed = 2.0f; // The NPC's speed
private UnityEngine.AI.NavMeshAgent agent;
private float timer;
void Start()
{
agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
transform.rotation = Quaternion.Euler(-90, 0, 0);
}
void Update()
{
// Update the destination every "updateFrequency" seconds
timer += Time.deltaTime;
if (timer >= updateFrequency)
{
timer = 0;
SetRandomDestination();
}
}
void SetRandomDestination()
{
Quaternion currentRotation = transform.rotation;
float y = currentRotation.eulerAngles.y;
float z = currentRotation.eulerAngles.z;
transform.rotation = Quaternion.Euler(-90, y, z);
Vector3 randomDirection = UnityEngine.Random.insideUnitSphere * 20.0f;
UnityEngine.AI.NavMeshHit hit;
UnityEngine.AI.NavMesh.SamplePosition(transform.position + randomDirection, out hit, 20.0f, UnityEngine.AI.NavMesh.AllAreas);
agent.destination = hit.position;
agent.speed = speed;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttackManagerScript : MonoBehaviour
{
BlazeAI blaze;
public HealthManagerScript healthManager;
public void AttackUnit(int damagePoints)
{
blaze.Hit(gameObject, true);
healthManager.healthPoints -= damagePoints;
Debug.Log(healthManager.healthPoints);
}
}
I've tried fixing this so many times but it keeps throwing the same error.. If anyone could help that would be greatly appreciated.
Error
NullReferenceException: Object reference not set to an instance of an object
AttackManagerScript.AttackUnit (System.Int32 damagePoints) (at Assets/AttackManagerScript.cs:13)
why is it -90?
Line 13 has a reference variable that is not assigned a value, that's all . . .
Look for any reference variables on that line and make sure they are assigned a value . . .
Why not make/set the rotation to 0. That should be it's default. If the x axis is -90, then that's probably when they're face down . . .
is an empty slot in a list null? If so, is this how I would check?
{
if (gameManager.spellQueueList[i] != null)
{
Debug.Log("test");
filledQueueSlots++;
}
}```
ok
whichever silly man told me to make a capsule collider array you have screwed me over for 2 weeks
for some reason this fucks with networking
are there ways other than manually defining a long list of [SerializeField] CapsuleColliders now
whatever ill do it
Depends on the contents of the list. They'd have their default values. Reference types would be that of null.
What errors are thrown? What's actually breaking? What do you mean by this?
are there ways other than ... now
Ways to do what?
hmm okay so its not working because when i do this:
gameManager.spellQueueList.Add(gameObject);
the object is still not being added for some reason
it stays null
nvm kind of using yalls as a rybby ducky nr
rn
Is there an error? @deep willow
it isnt the for loop
seems that it just isnt happy with multiple colliders
or collider array
one of the two
Likely you're looking at two different collections if there are no errors but the element isn't being added.
Classes that are inheritting another class inherit everything from that class, right? If so, how does Transform inherit Component if Component has a Transform as a property?
Also, you ought to use the length of the array rather than some arbitrary value for iteratively accessing members of the array. Else you could possibly get index out of range errors. Or at least constrain i by the length of the array as well.
Every object has a transform component. Every component placed on an object will know this transform component - Unity provided to us.
Transform just so happens to also be a component. So it'll have a reference to itself.
Through the inherited Component class
Objects don't have transforms https://docs.unity3d.com/ScriptReference/Object.html
You're referring to members and not components..
An object will always have a transform component
Implies "Unity Game Object"
GameObjects do
im trying to understand how scripts access references so im going down the inheritance chain
The property merely returns a reference of the actual component on the object.
from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Scripting/Component.bindings.cs
is this understandable or is it some internal unity thing
I've attached my code and a video demonstrating the issue.
The "add item" button places two seeds in the players inventory of a different type.
The code instantiates the panels you see beneath the "plant seed" UI in the GIF image.
The intention is that no matter how many seeds you have in your inventory, only one panel will instantiate per seed, so the screen is not flooded with panels.
However, as the GIF demonstrates, selecting the right-most seed causes a bug where only one panel is instantiated despite multiple seeds being in the player inventory.
Selecting the left-most seed causes the panels to display correctly again. I do not understand.
Full code is here: https://wtools.io/paste-code/bJzl
This is something the Unity team has wanted to change for a long time
They finally managed it with rigidbody, but they do have their eyes on transform..
do you know of any good resources for learning how unity works beside docs.unity3d.com
or do i really only need the docs
!learn
๐งโ๐ซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
most of those are beginner tutorials on how to make template games though, right?
I got by with only the docs, but I started in 3.x, and their documentation and tutorials were a lot better at the time
There are advanced concepts as well. You wont learn the actual internals since well unity is closed source. But plenty of the packages such as the SRPs are open on github
I'm not sure what you're looking into or asking, specifically. Properties are simply methods under the hood. In this instance, it returns a reference to the Transform component on the object. I do not know the underlying means of which it acquires the reference. Could probably just assume it caches it once after the component is added to the object or acquires it after first call to the transform property (they aren't likely calling get component for Transform every time the property is used - if so, they need to stop doing so as the Transform of an object cannot change). Knowing what you're concerned about would better help us answer your question. Likely there's some sort of misunderstanding.
would learning CLR or .NET help with programming in unity or am I just about fine with random searches to leanr.microsoft.com or "learn c# in 4 hours," "this is what delegates are!" kind of videos
if i were to look up how c# handles garbage collection would that be helpful
Build your game then profile afterwards.
Yes, and a bit of no. Traditional .NET uses a lot more static fields, getter/setters and has a different set of patterns overall. But if you were good at .NET, you will learn the Unity way of things much much quicker
blaze.enemyToAttack.gameObject.tag = "Dead";
Is this how I would change a gameobjects tag? Because it's not working?
Yes, provided it is a valid tag though mind you
It has to be a tag already specified in the Editor, and caps matters for it
I've created the tag I haven't given it to anything and also i've got the capitalization right and it doesn't work
Offhand the code looks just fine to me. I'd assume something else is somehow.kcmkng it
is the line being called?
like... put a log after it
or check with debugger
There are probably better ways to store if an enemy is dead btw.
ive fixed it
there isn't for the ai framework im using
Hey guys. Having issues with lists atm and google isnt helping me with this one. It must not be a common issue.
Im getting all colliders with Physics2D.OverlapCircleAll and thats all working correctly but its not putting them into a list in order. Trying to find the first one in the list by foreach (Collider2D col in colliders) {} but watching in the inspector normally the 3rd or 4th collider will get thrown in element 2 in stead of becoming the new element 0. So when I remove an element (out of range) its no longer detecting the next furthest collider.
Is this intended? Doesnt seem to be a common issue that I can find.
Physics2D.OverlapCircleAll returns an array, not a list. Lists wouldn't have this problem normally. Can you show your code? Seems very strange.
Sorry yes its an array. I was working with lists before. Here is the update function.
colliders = Physics2D.OverlapCircleAll(transform.position, range, mask);
foreach (Collider2D col in colliders) {
Debug.Log(col.name + " Has been found");
if (selectTarget == targetSelect.First) {
currentTarget = colliders[colliders.Length -1].gameObject;
}
}
if (colliders.Length == 0) {
currentTarget = null;
}
}
#archived-networking probably. The pins there should help you further.
cs or csharp @opal pine
I don't understand the problem in regards to your story.
if (selectTarget == targetSelect.First) { this whole part is unspecified.
Then you set your target to the last one in the colliders array.
Your foreach seems fine.
Very sorry for the sloppy screenshot.
As you can see on the inspector I've highlighted the 2nd element but in the Hierarchy its highlighting the last spawned gameobject
OverlapCircle don't care about the hierarchy
Why does the order of the hierarchy matter?
Thats just an enum. I have to select last to grab the first add array. But when that first array goes away its not in order that it gets added
Cause then it will select the next first gameobject.
What're you trying to do.. find the closest one?
just trying to find the first one. But as the array gets smaller I want it to find the next "first" one. Not a random one in the list because its been added in the wrong element
But OverlapCircle would remove it the next frame anyhow.
First spawned object. Yes in front
I got a problem where one of my raycasts returns a false positive. It returns true when it collides with layers not defined in platformLayerMask variable, which is set to default layer in the unity editor.
But the weird thing is that my other raycast doesn't return a false positive...
Anyone knows what the problem could be?
private bool IsBlocked()
{
RaycastHit2D raycastHit = Physics2D.Raycast(collider2D.bounds.center, Vector2.right * movementDirection, platformLayerMask);
return raycastHit.collider != null;
}
private bool IsGrounded()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(collider2D.bounds.center, collider2D.bounds.size - new Vector3(0.1f, 0f, 0f), 0f, Vector2.down, 0.2f, platformLayerMask);
return raycastHit.collider != null;
}
Put some value on each object, then you'd be able to evaluate that object to see who's the highest priority
if (selectTarget == targetSelect.First) { this is either true for everything in the array or for none, it also uses nothing of what you are iterating over. So the foreach also doesn't make sense.
Else you'll need to have some way to weigh which object is first.
public enum targetSelect {First, Last, MostHealth, LeastHealth, MostArmour, LeastArmour, MostShield, LeastShield}
public targetSelect selectTarget;
That if (selectTarget == targetSelect.First) has nothing to do with the array being added. I just didnt think when you add something to an array it would be added in a random spot
Hello guys
The main branch is old and it has alot of glitches so i want to delete it and make (The-work) branch to be the main branch
i dont whant to merge it becuase the main branch is very old and alot of glitches
So if your point is that the order of the array that Physics2D.OverlapCircleAll gives is unspecified, you are right.
Well that doesnt help me haha. Its so weird that it just wouldnt add any new elements in the array at the end or the start.
Guess Ill have to do a check that grabs all objects then checks each one with distance rather then relying on it being added in order that is finds the colliders
No it's not weird. You are dumping away the array and making a new one each frame. Then it scans the world again for colliders. It maybe has some scan order, don't know about the internals, but if it scans from top left to bottom right, the triangles will still switch places all the time.
Well, what I would do is give the enemies an enemy script. One of the values is how far they are on the path. Get the biggest number for the First.
Inverse it for Last. Enemy script also has values for Health, Armor and Shield. foreach over it and make a choice on that.
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);
You dump your layermask value into thedistance.
Thank you so much! I have spent way too much time on this
What's a quick way to generate a mesh along a spline? A simple flat thing like a road will do.
My current code is
Mesh GenerateMesh()
{
Mesh outMesh = new();
List<Vector3> verts = new();
int pointsRange = ((int)math.floor(container.Spline.GetLength() * 10));
for (int i = 0; i < pointsRange; i++)
{
container.Spline.Evaluate(i / pointsRange, out var pos, out _, out var up);
verts.Add(pos + (up * grabLength)); //Add far point
verts.Add(pos); //Add point on spline
}
int[] tris = Enumerable.Range(0, verts.Count - (verts.Count % 3)).Select(x => x).ToArray(); //The mod is to cut off the last triangle if there arent enough points
outMesh.vertices = verts.ToArray();
outMesh.triangles = tris;
return outMesh;
}
I am purposefully generating it only to one side
if that works that s pretty quick
I'm making a mesh for a Gizmos Drawmesh here, but I can't find it anywhere in my scene, so I can only conclude im not doing somethign right
I also tried wiremesh in case it was being affected by backface culling
I've never used gizmos.drawwiremesh I would try
- Debuging the outMesh.vertices.Length
-Creating a mesh and looking at it in scene view with wireframe on
-Writing out every point of the mesh and check if something is fishy
How can I access the animation state from my animator through script, so that I can modify its speed?
enable parameter checkbox, set parameter via script
No need for parameter checkbox for just modyfing the speed
animator.speed
that will affect all states
animation["Idle"].speed for example
hmmm I think the animation clips are shared, so that would probably modify the clip's speed for all animators that use that state. I haven't tried that though
Yea if you are using the same animation clip attached to different object i believe it'll modify the speed in both
does anyone know how I would do this? I have a value "20". I have another value that I will call "balance". what I want to do it lower 20 by 1 for every power of 10 "balance" that I have
I know it's logarithmic, but I don't know the syntax or how this would look in unity
in C# that is
//initialValue is the 20
initialValue -= Mathf.FloorToInt(Mathf.Log10(balance));
i think that should work
Guys can you help me with an error that i'm getting?
๐ 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.
I am getting "NullReferenceException: Object reference not set to an instance of an object Player_Movement.Update () (at Assets/Scripts/Player_Movement.cs:28)"
with the line that references like
if (Input.GetKeyDown(KeyCode.LeftControl) && CoinScript.CoinCounter > 5)
{
RUN = 2f;
CoinScript.CoinCounter -= 5;
Invoke("Walk",RunTime);
}
I referenced the CoinScript
I have referenced it in the editor
line 28 the if?
you sure you are not changing CoinScript anywhere in code?
In what sense?
I putted at the start CoinScript = GetComponent<Coin>();
just for autonomation
so does the gameobject that has the Player_Movement also have the Coin script?
Also what I'm trying to do is accessing a variable in the script
No
they're separated
....then that is why it is erroring
GetComponent<Coin>() is returning null as that script isnt on that gameobject
I'll try it out, thanks!
hi, i'm trying to procedural generate a map but i'm having problems with adding colliders, when i add a mesh collider it just goes like this
how difficult is the input system to learn ?
Thanks
I am new to this and I am making a game for the global games jam
Did you reference the mesh in the mesh collider mesh property?
i did something, no idea what, but it's fixed now, thanks for responding though ๐
also i think that i had put the mesh in the mesh collider property but again, i have no idea what i did
It will depend on your ability. I just switched over my game from the old system to the new system over a couple hours yesterday.
Hello, is there a way of change color of the child image (Icon) when I hover the parent Buton?
Right now it changes the green circle color when I hover, but I also want to change the leaf icon color
How can I make a simple player character movement with old input system ?
Performance of collider without rigidbody vs collider with static rigidbody?
there are quite possibly hundreds of tutorials that show you how to do that
Hi guys! can someone help me to convert an image? unfortunately I don't know how to program ๐ญ thanks
I need to convert a .texture2D file to .exr
Pretty sure it was set to convex earlier
Hello, I want to create a static function that can be called by any class, it is supposed to compare the tag of something of any possible type to another tag and then basically assign something to another thing, no matter the type. As an example, I have the function
if (tmproText.CompareTag(TagsManager.AchievementNameTag))
{
tmproText.text = achievement.Title;
}```
i'd want to create a static function that looks like:
```cs
void CompareAndAssign(firstThing, string TagToCompareFirstThingTo, thingLeftOfEqual, thingRightOfEqual)
{
if(firstThing.CompareTag(TagToCompareFirstThingTo))
{
thingleftOfEqual = thingRightOfEqual;
}
}```
So in my example, I'd basically only have to call CompareAndAssign(tmproText, TagsManager.AchievementNameTag, tmproText.text, achievement.Title)
However, I have no idea how this is possible, help would be very much appreciated, thanks in advance ๐
!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.
Thanks, thought it only needed the cs ๐
your static method does not have types for 3 of the parameters . . .
yeah, cause I want to create a function where I can input things of any possible type into it, is that possible and if so, how?
those params need to be of a type that are compatible . . .
everything derives from object but you'd have no idea what the actual type is. you can't confidently assign one value to another with receiving errors if they're aren't the same type . . .
you need to constrain the type to smth all of your input will have in common . . .
you're main goal is to compare tags. tag is a GameObject property, so why not use that type?
do you happen to know if textmeshpro for example is derived from gameObject, thus if I use gameObject for my type, would it work with textmeshpro
no, it's not, and you can easily look that up . . .
that doesn't make sense; TextMeshPro is a component . . .
you can see that from your inspector . . .
So what can I do in order that my function works?
void CompareAndAssign(object firstThing, string TagToCompareFirstThingTo, ref object thingLeftOfEqual, object thingRightOfEqual)
{
try
{
if (firstThing.CompareTag(TagToCompareFirstThingTo))
{
thingLeftOfEqual = thingRightOfEqual;
}
}
catch
{
Debug.LogWarning(thingLeftOfEqual + " can not be assigned to " + thingRightOfEqual);
}
}
Based on what you said I tried to adjust my function, I decided to use object as GameObject is not compatible, like you stated, however how can I use CompareTag with the class object, is there and thing like firstThing.TryGetComponent<GameObject>(), that might be possible?
Wait, just relized I could just input tmpro.gameObject instead of just tmpro, thus gameObject is a viable option as my first parameter
that's what i mentioned earlier . . .
i said using object doesn't make sense because you don't know what the actual type is that you are passing in . . .
Hey, how can i change without script the transform of a child gameobject without changing his parent's transform..? It doesn't work for me ! :/
animation
Yeah, just didn't see how that would work with things like TMProText at first, but I can just use TMProText.gameObject, object would work as 3rd and 4th parameter though, wouldn't it?
fr ?
@next crypt what if the first param is a GameObject and the second param is a c# class? they're not compatible . . .
or use the inspector idk
i have the case in another scenes, and it works pretty well in the inspector, but not on another scene, it's so weird
the child can move independently of its parent. you can use code or an animation . . .
the second is a string because it is always only used in the brackets of comparetag()
And without code?
idk ur asking something about without code in a code channel
i gave an answer for without code. read my message again . . .
Yeah but in another scene, i'm not using animations, or code and i can move the child independently in the inspector, but not on my current scene, that's weird xD
i see that, but why are you assigning one variable to another? what is that for?
huh, this doesn't make sense? how do you expect to move smth if you don't use code or the inspector to animate it? i don't follow what you're trying to do . . .
Where is player model at?
I basically want to assign a value to another value if compareTag returns true, but on top of that do lots of other stuff if compareTag is true, in order to write less code I want to create a function that assigns thing1 to thing2 and does all the other stuff below
The function seems to work now btw, thanks for the help! ๐
I mean, i just want to move it in scene view, like drag my child to move it downwards xD, i can show u screenshots if you need
okay, but don't use try/catch, just log if the statement isn't true . . .
I mean, the child object is "local" to parent, and i don't want that
then don't make it a child . . .
that's just how parenting works . . .
that isn't really used for checking if the statement isn't true, but instead checking if thingLeftOfEqual and thingRightOfEqual is compatible, however I just realized that if it isn't compatible, an error appears in visual studio anyway, so try is unnecessairy
i swear that i have another parent, which i can move independently the child on inspector, without affecting his parent, thats' why i'm writing here xD
yup . . .
a child can always move independently of its parent . . .
moving a parent will affect the child . . .
the first screen is the position of the player, and the second one, it's the position of the player after moving up the "graphics" child to the good Y pos
i swear it's weird bro
ok for some reason i just redid the manipulation as i did just for the screens, and it works
wtf
i'm not drunk xD
not sure what the problem is. you're probably just bugging, but ask in #๐ปโunity-talk as this isn't a code question . . .
Yeah it was bugging
Hello, I don't know if this is the correct channel to post my code for review but I feel like I'm doing some stuff wrong (performance wise) with this code, I'd appreciate if anyone can pinpoint any bad practices in my code!
public class EnemyController : MonoBehaviour
{
[SerializeField] float attackRange = 5f;
private void Update()
{
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
Transform currentPlayer = GetClosestPlayer(players);
if (GetDistance(currentPlayer) < attackRange)
{
print("Can attack");
}
}
Transform GetClosestPlayer(GameObject[] players)
{
Transform nearestPlayer = null;
float minDist = Mathf.Infinity;
foreach (GameObject player in players)
{
float distance = Vector3.Distance(player.transform.position, transform.position);
if (distance < minDist)
{
nearestPlayer = player.transform;
minDist = distance;
}
}
return nearestPlayer;
}
private float GetDistance(Transform player)
{
return Vector3.Distance(player.position, transform.position);
}
}
hello guys so i just finished watching a video about headbobbing and in the video the headbobbing is normal but mine is like this:
this the code that does the headbobbing:
private void HandleHeadbob()
{
if (!characterController.isGrounded) return;
if (Mathf.Abs(moveDirection.x) > 0.1f || Mathf.Abs(moveDirection.z) > 0.1f)
{
timer += Time.deltaTime * BobSpeed;
playerCamera.transform.localPosition = new Vector3(
playerCamera.transform.localPosition.x,
defaultYPos + Mathf.Sin(timer) * BobSpeed,
playerCamera.transform.localPosition.z
);
}
}
I would bet dollars to donuts that in your video:
Mathf.Sin(timer) * BobSpeed
is actually
Mathf.Sin(timer)
or
Mathf.Sin(timer) * BounceAmplitude < which is what you should do here to change the amplitude
Remember BobSpeed is already taken account of with this: timer += Time.deltaTime * BobSpeed;
this is the code from the video he uses the ternary operators there but i chose to put it in the BobSpeed variable but my code is exactly the same as the one in the video
no it's not
again
like I said
you're using bobSpeed there
he's using bobAmount there
different variable
oh
Hey so I've made a health system, mostly, but I'm struggling to add immunity for a certain amount of time after being hit. https://gdl.space/gicolawemi.cs Can anyone help?
now the headbob doesn't work at all
what did you set bobAmount to
and what code did you end up with
debug it
this is the code now:
if (!characterController.isGrounded) return;
if (Mathf.Abs(moveDirection.x) > 0.1f || Mathf.Abs(moveDirection.z) > 0.1f)
{
timer += Time.deltaTime * BobAmount;
playerCamera.transform.localPosition = new Vector3(
playerCamera.transform.localPosition.x,
defaultYPos + Mathf.Sin(timer) * BobAmount,
playerCamera.transform.localPosition.z
);
}
and these are the bobbing amounts
why did you switch timer += Time.deltaTime * BobAmount; to use BobAmount???
this is really just you not being careful and not copying the code properly / paying attention to what you're doing
yeah sorry it works now
Hello, I'm having a problem with getting my Player to the next scene. I put everything how it's supposed to be but still nothing is working, I don't know if I missed something or if something is wrong with the code.
(I put the Is Trigger on the object the player has to go through, and I put the scenes is build settings)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneRight : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
int sceneBuildIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(sceneBuildIndex + 1);
}
}
}
add Debug.Log outside the if statement to see what's going on
This is where you start debugging
Debug.Log($"Collided with {other.name} with tag {other.tag}");```
you can't just stare at code and guess. Debugging is the only way forward
Can anyone help me with this
Code?
you'd have to actually tell us what's going wrong
I tested the immunity frames to be 100 on start, and the immunity frames went straight down to -0.02 in the console
start a coroutine that waits X seconds and have a global boolean or use enums to track whether you should be immune
I assume you want to start a Coroutine after the character was hit that would trigger a variable "isImmune" and make it true , then after a certain amount of time, make it false again then in your collision system you check If isImmune is false
your code is saying "frames" but I think you actually mean "seconds"
you need to figure out which one you want.
and frames is probably not it
Yeah Im looking for seconds
get it straight in your head what you're dealing with
and make your code reflect that and clearly state it
to reduce confusion
Yeah my bad
Also, in your Coroutine don't use Wait for seconds, If you pause the game by making the Time.timescale = 0, your Coroutine will still run and set the bool back to false after the set amount of time
you can def use waittforseconds. be smart be aware of your coroutines
store it or use StopAllCouroutines on the behavior
Using waitForSeconds is not a good idea if the game has a pause system, which most likely has, it's better to use WaitForFixedUpdate and have a value that increments until it reaches the amount of time the player should be immuned for
That, is considering the pause system just set the TimeScale to 0
Thatโs how the model is, if the X is 0 theyโll be on their faces but if itโs -90 theyโre standing up
Something like this :
don't forget to add a yield break if the player is already immune, better safe than sorry
Is there a proper way to transfer ownership of network game object from client to host and in opposite ? For some reason with this code I am getting, Client wrote to NetworkVariable ... without permission, Why I am getting this error, (I am trying to transfer ownership via Server rpc) ?
Hello i got this error in Google Play Console After trying to upload an aab file:
APK or Android App Bundle which has an activity, activity alias, service, or broadcast receiver with intent filter, but without the 'android: exported' property set. This file can't be installed on Android 12 or higher. See developer.android.com/about/versions/12/behavior-changes-12#exported
You're adding deltaTime but using WaitForFixedUpdate which relies on fixedDeltaTime. The added deltaTime value is not consistent with the next iteration (call to run the coroutine) . . .
Oh, then replacing deltaTime by fixedDeltaTime should do it? I wasn't aware of that
yeah, but there are many different ways to do it. they can yield return null; and use deltaTime. if timeScale is set 0, it will not add anything to the timer (variable), resulting in a stalled state for the coroutine (paused). you can also set the keepWaiting property to suspend the coroutine. using WaitForFixedUpdate means you're relying on FixedUpdate, but that should only be used for physics-based code (unless you're doing smth deterministic) . . .
Yeah my first approach was to use yield return null coupled with incrementing the number with time.deltaTime, but then when I saw I could just wait for the fixed update it seemed to be more appropriate, guess it works, but didn't know it kept running the coroutine, I though it really just was waiting for the next fixed update
if they do want the coroutine to run while paused, they'd use the Realtime version of the yield instruction . . .
you can use WaitForFixedUpdate to wait for the next FixedUpdate but the deltaTime added needs to be correct. that's all i was mentioning . . .
Okay, so it means the deltaTime is not 0 when TimeScale is 0?
I don't get it, it has to stay at 0 since the value doesn't increment anymore when timeScale is 0
And since it's a delta, it has to be some sort of interpolation between one moment to the other? So deltaTime is not going to change by much?
Or am missing something?
Hey yall, I have a ton of animations and I dont want to set them all up in an animator, is there any way I can change blend tree animations through script on runtime?
I'm guessing "AddChild"
No, didn't say that. deltaTime will return 0 when timeScale is 0. If you add deltaTime to the timer and wait until the next FixedUpdate โ the deltaTime between fixed updates are constant at 0.02 which is different from the deltaTime you added to the timer (since it's at a variable rate) โ the value is not consistent when the caller returns to the coroutine . . .
Hey, I have next to no experience with animations, but I would check out iHeartGameDev. He has generally very good tutorials, including animations.
For scripting animations I hear Animancer is a good alternative, but I have no idea if that's an up-to-date opinion.
Hello everyone! I'm having a problem with Unity and still haven't found the solution. When I first start my game, there is a very short freeze while rendering any UI element. Sometimes this can be in milliseconds, sometimes it can be in seconds. What could be the reason for this?
https://youtu.be/-wbs0EYGkgA
how can I install this package? https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.0/manual/index.html
Unity is executing all of your start/awake functions, the UI renderer is just trying to keep up with everything else going on. If you have a game manager you would generally load all of your assets in before anything renders and the player can move
So how can I preload all the items? Sorry, I'm very new to Unity.
I just switch over to the new unity input system and Im having trouble converting my code would anyone know how to get this if statement to work?
if (context.performed)
{
jumpBufferCounter = jumpBufferTime;
}
else
{
jumpBufferCounter -= Time.deltaTime;
}
A game manager and game loop is a bit harder to explain if you're new to unity but do have a look at the SOLID principles and learn about different programming patterns. It's a lot but will help your coding in general to be more efficient and extendable. For now have a look at this, it looks like Unity can preload selected assets and make them available in memory from the start of the game: https://forum.unity.com/threads/how-does-preloaded-assets-in-player-settings-work.318259/
take a look at this too, it breaks down patterns and best practices pretty well https://blog.unity.com/games/level-up-your-code-with-game-programming-patterns
hey guys i have a quick question if someone can help me out
if you can dm i will explain it
mb yo
do canvases work when instantiated?
yes
specifically if it has a button
because i instantiated a canvas with a button and it doesnt work
is there an event system in the scene?
I am having trouble finding the cause of a pathfinding issue with my NavMeshAgent.
Goal: find the shortest NavMeshPath to the Vector3 target
Problem: when the target (my player character) is in motion, the pathfinding returns a NavMeshPath. If the target is not in motion, it returns null.
I use the following method to find the shortest path to the player position:
private NavMeshPath GetShortestPath(Vector3 target)
{
var path = new NavMeshPath();
if (NavMesh.CalculatePath(transform.position, target, _agent.areaMask, path))
{
return path;
}
return null;
}
Has anyone encountered this problem or has any ideas what I can do to find the issue?
yea
Use Debug mode with the Event System selected and see where what the active object is.
Common issue is that you did not have a GraphicsRaycaster component on the Canvas
so i need to animate a button on my main menu to smoothly scale up when hovered over and smoothly scale down when the mouse exists, i tried using animator to record a scale up and scale down- but im not able to figure out how to make the animation only run once and stay on the ending keyframe while the mouse is hovering over the collider, as well as scale down and stay on the regular scaled down keyframe after the mouse exits the collider
Animator animator;
public bool mouseOver = false;
void Start() {
animator = GetComponent<Animator>();
}
void Update()
{
if(mouseOver==true)
{
animator.SetTrigger("MouseEnter");
animator.ResetTrigger("MouseExit");
}
if(mouseOver==false)
{
animator.ResetTrigger("MouseEnter");
animator.SetTrigger("MouseExit");
}
}
public void OnPointerEnter(PointerEventData eventData) {
mouseOver=true;
}
public void OnPointerExit(PointerEventData eventData) {
mouseOver=false;
}
}
not sure how to separate the code block sorry
this is a code block
!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.
describe the issues
"have issues" is incredibly vague.
im just asking in general cuz like
ive had to do a lot of bs to get it working
for example
I am not a huge fan of it personally, I think it can be easier but it's okay now that I have done it many times
i have an instantiated player and the player gets disabled through gameplay so i cant have a player input on it
this is a design issue
lol is it
you can put player inputs on a different object
yea i did that
i put another object in the player prefab that sets its parent to nul
but it just feels so weird
to do that
you could have it as a separate prefab
i just wanted to know if i was bad or if everyone has to deal with new input system bs
oh is this the new input system? I haven't used it extensively
yea
still sounds like a design issue tbh
i use the input system exclusively and have never run into issues like that. you just need to learn how it works so that you can use it effectively
how is it a design issue tho?
in my current project, I have a Player GO that exists throughout the game that stores all things related to a single player (my game is multiplayer). Then, PlayerCharacter is a separate object that receives only the inputs it needs
what is the issue exactly and what are you trying to accomplish?
i mean you haven't really even described the actual issue. you've just said you cannot put the player input component on the player object because you disable the player. but why is that an issue
i mean there isnt an issue because i did the weird workaround
maybe its just a personal thing idk it feels weird to do something like that
is there a way to append functions to player input events?
well considering you haven't even said what the issue was then nobody here can possibly know what you actually need to do
yeah I'm not sure what you are trying to do and what issue you are working around
i might be rambling a bit sorry lol

