#archived-code-general
1 messages · Page 136 of 1
obviously it isnt there yet. Because dont know how exactly to work with it. No guides
You don't need 3rd party tutorials. If you understand why ECS is performant in the first place, and what it's doing with the memory, it's very easy to dive into.
both of which the unity docs show very clearly.
by not storing it on the device at all
Maybe then using the android keystore, although i dont know much about it
I think the only other option would be hiding the key, or writing it to a place where your application only has read permissions
I see something about internal storage, where users cant just access the file from your phone. but yea someone could just open it up in other ways
I mean regardless of how u store it, if this information is important enough, someone would break apart your app and find how its stored no matter what you do
if its just local game data, with no online highscores or purchase system then i wouldnt really worry about this
Yea i wouldnt waste time on this if its not real money or online at all
most wouldnt even know how to edit their files in the first place, even if they were handed the encryption key. Anyone who wants to edit it and is dedicated enough to even find the key in the first place to edit data for a local game is desparate enough id probably help them edit their file
im unsure what you mean tbh
you would be encrypting when saving.. if that answers the question. I really dont know what manually would even involve here
hey, ```` barrel.transform.RotateAround(barrel.transform.position,barrel.transform.right,Time.deltaTime*rotationSpedRad);
transform.rotate is also translating the object to much
i guess i have to set the transform.position afterward, or add a joint. but i really dont get it. i thought rotateAround should fix this, but its not
I have a question, can we invoke an event from another class? suppose an event is written in ClassA and we are trying to invoke it in ClassB, is that possible?
why not?
Because I am getting an error
The event 'ScriptB.UpdateScoreUIEvent' can only appear on the left hand side of += or -= (except when used from within the type 'ScriptB')
using System;
using UnityEngine;
public class ScriptB : MonoBehaviour
{
public static event Action UpdateScoreUIEvent;
private void OnEnable() {
UpdateScoreUIEvent += UpdateScoreUI;
}
private void OnDisable() {
UpdateScoreUIEvent -= UpdateScoreUI;
}
private void UpdateScoreUI() {
print("Updated Score UI");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptA : MonoBehaviour
{
private void Start() {
Invoke("InvokeEvent", 3);
}
private void InvokeEvent() {
ScriptB.UpdateScoreUIEvent?.Invoke();
}
}
I've made a finite state machine via interfaces. I have a StateController monobehaviour and two IStates: RoamState and ChaseState. The problem is the states have a lot of logic and require data from other scripts to work. As they are just IStates and not monobehaviours they cannot reference the needed scripts in Awake() so the references have to be acquired in StateController and then passed to the states as a parameter in the OnEnter() and UpdateState() functions. At this point there are lots of parameters being passed in and it feels quite messy. Is there perhaps a better approach that circumvents this issue?
maybe you can use a gameManager that stores the data, rather than passing it in?
you cannot reference them, but you can get them in awake() with getComponent and/or object.find.
sooner or later people run in to this problem and they use dictionaries and a gameManager to avoid the issues
@royal pulsar you can stores your dictionaries inside a list
@royal pulsar https://learn.unity.com/tutorial/lists-and-dictionaries
have you tried to call a method of scriptB that invokes it? if you cant invoke directly
Can someone help me with this? #💻┃code-beginner message
Please don't crosspost
And your question doesn't seem code related. Ask in #💻┃unity-talk
ok sry
Yes I can do that but I just wanted to know in general whether it is possible invoke an event from another class or not
I a trying to make my Player able to lean left and right (like in Rainbow 6 siege as an example) but I can figure out how. Can some please help me.
Will asset be included to build if it was linked in field like below?
#if UNITY_EDITOR
public GameObject Prefab;
#endif
No
It's a bad idea to exclude serialised data using preprocessor ifs
The engine dislikes you doing it and it can cause random warnings to be present in your project, along with miscellaneous things going wrong
what is the preferred way then?
Don't serialize the field in a runtime object if it's intended for the editor only
How then I access to this asset in editor?
Asset database is one option
Ok, what if I want it to development build but not to production?
Pre build scripts that swap assets in/out is usually my approach
our naming convention for commits is beyond professional.
Is there any way to add / remove triangles to meshes at runtime? What about bones too? If so is there anywhere I can read up on this
Wanted to make a snake that changes dynamically in length but connected capsules just ain't gonna do it lol
you can use animations
What you are describing is SkinnedMesh.
I see. Is there a way I can add objects to deform the mesh though?
Like not just the bones
Sure
I never done it, however that would be strange if it was not possible.
At the end, you could implement your own API if needed.
is there a way to add outlines to a ui sprite but not that?
what are you thinking of here?
just extra transforms that deform the mesh?
Yeyeye
when you say "objects to deform the mesh", I think of actual softbody physics
ok, that's simpler
He is doing a snake.
I have also not done this, but fundamentally, you just need to make sure that the mesh has vertex weights that correspond to these new "bones"
that's the part I'm not sure about
That's fair enough I'll look about on the docs. Thank you for the advice
Loading resources is about to drive me crazy.
LoadAll<> didn't work so now I'm specyfying where exactly the asset is so that it can load it and yet it fails once again.
Does anyone have any idea why does this happen (and how to fix this)?
Show the inspector for that so?
You mean this?
Can you screenshot your resources folder in File Explorer
Idk if that's what you meant but here you are
do you have the same problem loading from Scriptable Objects or Prefabs?
No, there haven't been any problems with loading from Scriptable Objects so far if I remember correctly
The issue is only with loading an "instance" from Scriptable Singletons
The thing is, loading from Scriptable Objects only takes place if loading from Scriptable Singletons ends up successfully, so I can't really tell if there wouldn't be any problems with loading them separately
Worst case scenario I'll just place a "Scriptable Singleton Holder" GameObject into the scene and reference my libraries there, but I'd preferably like to just Load them from the files as I mostly need to do that while not in playtest mode.
AttackLibrary_SS al = Resources.Load<AttackLibrary_SS>("Scriptable Singletons/AttackLibrary");
works for me
Welp, I've switched to
public class AttackLibrary_SS : ScriptableSingleton<AttackLibrary_SS>
``` and deleted my `instance` definition to let Unity handle this
So far it works, we'll see how it goes.
Idk what's wrong with Resources.Load, sometimes it works, sometimes it doesn't.
It also worked for me for a while, then decided to stop
Also, idk if it means anything, but I've been calling the instance from within my AssetPostProcessor
quick question, if i had a variable field which accepts a Class, any script that inherits from said class should be accepted into that field right?
i cant figure out how it works, and i probably have it wrong, but thats what was logical to my brain
Currently have a script called AltarBuffEffect, and a script called HealthBuff which inherits from AltarBuffEffect, but I cant drag it into a field of type AltarBuffEffect
simply bcos SCriptableSingleton is not a physical asset... I mean, it is if you defined the FilePath
and it's Editor-only
and you don't need to loadResources at all
MyScriptableSingleton.instance is all you need
I was using ScriptableObject as a Singleton, so it was a physical asset.
It's just now that I've switched to an actual ScriptableSingleton which is indeed Editor-only.
Hello, if i have an OnTriggerStay2D
that call a function that turn a boolean true
and start coroutine
while boolean is true playertakedamage
will i call the coroutine multiple time?
if OnTriggerStay2D invokes the coroutine, yes.
oh i see
If you enable it through OnTriggerEnter, and disable the coroutine itself when the bool is set to false, you wont have multiple instances of the coroutine, and it wont continue unless the bool is true
Ok pretty simple, thx !
or rather, no way other than attaching the script to a game object, is there any way i can do it without creating a prefab for it?
why does it need to be encrypted exactly?
The easiest thing to do here is to just include the json file in the assets as a TextAsset. It will automatically be compiled into the main game binary blob
this is a plus in my opinion as a gamer but
¯_(ツ)_/¯
I know
I also mean that
it does get compiled into the binary blob
unless you very specifically place it into a StreamingAssets folder
exactly, so why do you care?
yes
I'm saying:
It is going to be compiled into the game data packed binary so it isn't going to be plain text anyway. But even if it was I wouldn't worry about it.
As a game developer I don't care if users cheat at solitaire.
it only hurts thmeselves
this pretty much
or they have fun doing it
if they want to cheat they'll cheat
either way - the user is having fun why would that upset me
getting this error when trying to add a package from github
Could not clone [https://github.com/itisnajim/SocketIOUnity.git]. Make sure [HEAD] is a valid branch name, tag or full commit hash on the remote registry. [NotFound].
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()```
Exactly - you only hurt yourself
can you share exactly which URL you used?
yes
it worked for another guy who sent me this link
not wokring for me
yeah it says to add the link in the package managaer
but the package isnt getting imported
well yeah you;re getting an error
yeah anyone knows how to fix it?
i read a thread about editing the manifest file , i will do that now. if theres any other way let me know
ok i tried some other packages as well
wont import any package from url
hey, which option did you select
add package from url
something might be weird with your git installation or configuration
also check for .gitconfig in your home directory
you might have some weird stuff in there
home directory of?
your computer
like - your user folder
/home/Username on mac or C:/Users/Username on windows I think?
helper = manager-core
[filter "lfs"]
clean = git-lfs clean -- %f
smudge = git-lfs smudge -- %f
process = git-lfs filter-process
required = true
[user]
name = *******
email = *******
name = *******
thats all there is in the .gitconfig
hmm that should all be fine I think
Hi, I'm currently using the A* pathfinding algorithm for my zombie ai. However, I'm facing an issue where the pathfinder does not recognize tilemap collider with a composite collider as a collider. As a result, the zombie clips into the tilemap. Is there any solution or fix for this problem?
which a* pathing are you talking about?
Im using Dijkstra’s Algorithm
A* is another algorithm from Dijkstra
im not pretty sure
different from*
ye then you used A*, not dij, a star is like a remade version of dij
well can you provide the code? or are you 100% sure you followed the tutorial
well, it sounds like you need to examine how you decide what areas are and aren't walkable
K gfu
thanks
Hey so I have a really weird issue. There's no errors being thrown, so it's got to be a bug somewhere with the logic of the code. Thing is it was working previously and now suddenly it doesn't anymore.
triangle.getCircumcircle().render(.05f);```
The issue is somewhere along this line of logic
The triangle.render() works absolutely fine, yet for some reason the render function for the circle objects do not work, despite the fact that they both use the same underlying render function within the Line objects used to represent edges.
You can see that all the triangles here are rendering despite the fact that the circles called immediately after them, are not.
have you confirmed that GetCircumcircle works correctly
circumcircle = new Circle(this.getCircumcenter(), Vector2.Distance(this.getCircumcenter(), this.getVertices()[0])); This is the line that creates the circumcircle, it's in the Triangle class in the link I posted. It doesn't throw any errors, and I know that the Circle class does work because the triangle generation is based on those circles.
sure, but that doesn't mean that circles are rendering correctly, or that the circumcircle is being generated correctly
verify both of these things
render a circle by itself, and do something to prove to yourself that the circumcircle contains valid points
I'm unsure what you mean by "generated correctly". The circumcircles are being generated correctly because if they weren't, the triangles would not be getting generated correctly.
The generation of the triangles is based on the circles of previous triangles
This is part of a delaunay triangulation algorithm.
well, you're currently in a situation where the circles aren't working
so you should rule out as many issues as possible
The rendering isn't working
i don't know how the rest of your code works, so I don't have any information beyond what that file contains
triangulator.getTriangles(); is where the triangles come from, presumably
what was the fix? sorry just got back
Definitely does not look that way, as you are not able to render it ?
It is not, that returns a list of generated triangles. The circles are created within the Triangle class, which I included in the paste.
I am not.
yes, and so i see no reason for "triangles work" to be proof of "circles work"
Then try to render a single, simple circle.
you can spend all day trying to convince me that X isn't the problem, but it'd be much more useful to just prove that X isn't the problem...
I did. It doesn't work.
Oh, so we now know that the render is most likely the issue.
As stated, the issue is not with the delaunaryTriangulation class.
That is what I said, yes.
by simply defining a circle yourself, rather than generating one from a triangle's circumcircle?
Yes. I used the Circle class directly.
That isn't relevant because of how the classes are designed, but you guys haven't looked at the classes because that code paste is long and you responded immediately.
If you could actually take a look at the logic
That'd be great
this indicated you were having a problem with rendering the triangles' circumcircles in particular
you should always simplify as much as possible
Cause I already stated the issue is with the rendering
i read through the code briefly. i did not carefully examine the logic.
We looked, however, must of the time there is no way that someone can fix bug just by looking code.
We are trying to eliminate issues.
suppose this somehow produced a bogus circle
again, simplify as much as possible
just try to draw a circle. nothing else.
no intermediates, no extra work.
i did, indeed, see that this was how the circumcircle was generated
The issue could potentially be from the: setSteps function.
oh
you set radius and center after calling setSteps
the circles have a radius and center of zero
Yes
the same problem returns
That might be it actually
are you using a custom solution or an asset?
a custom solution
that was definitely the issue. I knew it was some minor logic error somewhere.
Thank you.
this was not the case. always simplify your problems as much as possible to prevent this kind of thing from happening!
the first thing i do is generate a grid
and for each node*check if it is walkable or not
but with a composite collider
the check is always true
for (int i = 0; i < sizeX; i++)
{
for (int j = 0; j < sizeY; j++)
{
// ...
var walkable = !Physics2D.OverlapCircle(nodeCenter, nodeRadius - .1F, obstacleLayer);
// ....
}
}
It's weird though that it wouldn't spit out an error saying those variables weren't initialized.
no, since they're fields
fields get a default initialization
only local variables can be uninitialized
Interesting.
I think it's equivalent to writing T fieldName = default;
Well, thanks. One step closer to getting my triangulation algorithm working.
I hate algorithms. Hopefully I don't have to work on too many more after this.
ohh you're using colliders :\
i usually just use the obstacle tilemap to tell algo where obstacles are
or exclude them from the algo entirely
Hey guys, need help finding the positions of 4 corners of the rectangle drawn in red, i am trying to confine the view to the collider visible, currently i am using the far clip planes corners to confine the space but it is not giving me accurate results, if i can find the the points intersecting the cameras viewport extents and ground , i think i could achieve the result i want
are all uniquely decodable codes prefix codes?
nope
consider a language with two symbols, a and b, encoded as 0 and 01
0 is a prefix of 01
but it's still uniquely decodable as long as we can look ahead at least one character
I think you do have to have a prefix code to be able to uniquely decode without lookahead.
All prefix code are uniquely decodable, but not all uniquely decodable code are prefix code.
Note: Prefix code are instantaneously decodable.
I have this class in the script with another class withing the same namespace. Script called TypingField and first class called TypingField too. This TypingFieldHelper's Update method is not being called.
public class TypingFieldHelper : MonoBehaviour
{
private void Update()
{
print("nice");
}
}
you can only have one monobehaviour per file
no other way?
no, you need a second file for it
ok, thanks
Is it possible to get all methods that execute in the certain period of time?
I've made a method return a bool just so that I can check for it's completion.
And I think I used some weird lambda thing for coroutines in one spaghetti filled game.
But I dunno if Unity keeps track of all methods that execute somewhere.
Oh, maybe you could use event system for that sort of thing, dunno.
is it a question?
look into the profile analyzer
I have this base class that saves data to a save manager when the scene is unloaded. I have to access other components during this process, but they are destroyed before the method runs, resulting in a missing reference exception. No luck with execution order or SceneManager.sceneUnloaded :/
Here's the derived class https://hatebin.com/ppqmvpauws
Is there a solution to this?
I need help, whenever I start the game and click new game, it deletes my playerprefs, but when I click the back arrow to go back to the title screen and click new game, it doesn't delete my player prefs, someone help. https://pastebin.com/mCDR2bb6
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You might need to call PlayerPrefs.Save after you modify it
Will try that
also dont crosspost
Ok, it didnt work but here is vid of issue
take it in #💻┃code-beginner
Also I noticed that your first function is Update, so you are adding those listeners on every frame, dunno if that could mess up something but ye
I changed it to OnEnable
@radiant maple Stay in #💻┃code-beginner please.
ok
is it worth it to pool objects that i use to send damage info?
Just normal C# objects with data on them?
yeah
what does "send damage info" mean and how are these objects used?
And what is their lifecycle
(also are they structs? classes?)
anytime anything that takes damage aclass with info like the sender, reciever, damage, location... etc and
and they have a short lifetime
A struct should be fine
should you have mutable data in a struct?
why not
idk just thought yo werent supposed to
Why would they be mutable if you shouldn't mutate them
If the struct is very big and you're passing it to functions often, a class might be better to avoid copying
Hiya, I did some codey things using AssetDatabase functions and then lo and behold you can't compile that to android.... Obviously. So, I've moved to using Resources.Load which works to load the right assets, however I have a line to get the path/filename of an asset and use that later to load things....
path = AssetDatabase.GetAssetPath(asset);
Essentially I just want the filename of an asset I have exposed as a public variable in the editor. Any way to do this? Perhaps a script that when it's building just runs that AssetDatabase command and saves the output to a string in the component instead?
If you want immutable structs look into records
also based on your description of the data it doesn't sound like you need them to be mutable anyway
or readonly structs 🙃
i do agree however there is a field for the damage that i need to modify based on stuff
If you have exposed the asset as a reference in the inspector there is no need to use Resources.Load. You already have a reference to the asset.
just use it directly
It is for a localisation system and I have different folders for different languages.
So when I change language I want to load the same filename thing but in a different language folder
you will need to think of a different approach then, because this isn't going to work
Have you thought about using Unity's built in localization package?
Why not put it in a Resources folder?
we are using the localisation package for audio/visual assets but not for subtitles
so it is in a resources folder, but I still want to be able to ie:
Resources.Load(subtitles\EN\file.txt
Resources.Load(subtitles\ES\file.txt
etc
So why do you need to use assetdatabase instead of resources?
Oh wait I read the original question wrong
because, I need to GET the filename of the linked asset, in order to load the same named one in the resources folder.
I am using resources.load to get the assets, and this works, but I need to replace the AssetDatabase function which gives me the filename of the asset linked in the inspector
Yeah, you probably need to chose a different approach
Hey all so i am about to work on a game for Uni but trying to figure out how to do something that i can't seem to get my head wrapped around.
How would I go about making a fence prefab that during run time i can put into the scene to make a fence around a garden but I would want to implement it to be a free form kind of making your own fence due to the garden being a custom garden.
My best thoughts around making this happen is putting in a pole and then instantiate the fence prefab from that pole and allow it to be stretched by modifying its transform scale but clamping the x & z values so it can't go to far. Then once its finished being placed it drops another pole and the process repeats.
is there a function that calls when you update a particular field in the inspector? Like when I drag in an asset it just writes a private string which is the filename of that asset
and then use that instead
OnValidate
ooh
Remember the private field has to be serialized in order to be "remembered"
that might work. Thank you
Anyone know how I can get one end of my line renderer to stick to my player as it's moving and the other end to stick to the grapplePoint?
it makes the line when i click it but it doesn't continue following the players movement
also if i switch to a different grapplePoint object it will make a line from my player to the last grapplePoint that i used, not the new one
private void DrawGrapple() {
lr.enabled = grappler.enabled;
if (lr.enabled) return;
this only updates the points if you AREN'T drawing the line
that seems backwards...
I can't believe I missed that earlier 🤦♂️
thanks i missed the ! part before it lol
Is there a faster way I can check if an array (or any other collection, im fine with changing it) contains a type than using .Exists? I have an array of a base class and a function like this - is using Exists the fastest option in this case? Looking online, .Contains was suggested, but id need the object and I only have the type so im not sure how I could use contains without Linq (which would be more expensive), I also looked at a HashSet<SomeBaseClass> but same issue, I dont think I can check the type through it - normally this isnt a problem, but profiling suggests the number of AI using this function contributes the most to alloc
SomeBaseClass[] arr;
public bool HasClass(Type someType)
{
return arr.Exists(x => x.GetType().Equals(someType));
}
Hello, I noticed that Physics2D.RacastAll does't hit colliders that have offset the collider component. So for exaple a BoxCollider2D with offset (0, 0) is being detected by RaycastAll just fine, but the same collider with offset (-6.1875, 0.34375) is not detected. Is there a way to get around this? Is it a bug or should it be like that?
Maybe it should be reported to Unity staff? I digged in documentation and didn't found a word about such behaviour
As long as the distance, direction and layermask (if your using one) is correct, the offset shouldnt affect if it gets detected or not, if your using a layermask, you could try removing it to test, or moving the transform closer to your raycast origin and direction, how are you checking that it is not getting hit? For example, are you logging the array it returns?
Does the array contents change? If not caching is a quick fix
Dont crosspost and not a code question
The raycast is damaging enemies so I can easily see when it hits. But to better understand the issue I also logged raycasts outcomes. (the blue ray hitted both player and enemy but not the collider that is between them. The green lines on the picture is the box collider 2D)
Are you unable to use generic types instead? Or do you have to use reflection for the types?
var contains = arr.OfType<Foo>().Any();
var contains = arr.OfType<Foo>().Count() > 0;
var contains = arr.Any(v => v is Foo);
var contains = arr.FirstOrDefault(v => v is Foo) != null;
I will remove the layer mask to see how it works then, but since changing offset to (0, 0) works I don't think that the layer mask issue
Hmm, ill try and see if I can do a generic approach like that and check the profiler again
Can even do a for/foreach and do a manual check as well instead of linq. Really whatever works lol
I removed the layer mask and got same results. Seems like collider's offset is the only thing thats effecting raycast outcome
public void EnableColliders(GameObject Which, bool state)
{
var Cols = Which.GetComponentsInChildren<Collider>().ToList();
if (Which.GetComponent<Collider>())
{
Cols.Add(Which.GetComponent<Collider>());
}
foreach (Collider c in Cols)
{
c.enabled = state;
}
}
rate this function/10
looking for tips
GetComponentsInChildren already gets the collider on the initial object
good to know
It's very dumb
You also dont need to convert it to a list (because you dont need the check)
^
its the kind of thing which looks wierd but is actually very nice
alright cool
I think it's due to how it does recursion to where it isn't avoidable, but just a weird thing
i mean
GetComponentsInChildrenAndSelf
is pretty clunky
the parameter Which doesn't follow naming guidelines either
Yeah but at least you would know it includes self 
also it's kind of a weird name, but I guess it's fine
if you are worried about that, the rest of my scripts would cause you to implode
:)
what confuses me is that the second parameter is not CamelCase
Can't you just click through them and vs fixes it for you?
You can do that in rider
it should rename references usages too
what might screw you over is serialized fields
oh god
I
I public everything
its a very very bad habit
ill stop ranting about my bad code practices
oh god, that probably increases the size of your project and builds by quite a lot
maybe not project as it's already really big
im so sorry
🫠
basically
Love the random delegate declaration
what where
where?
it just controls the bars, because the health is stored here
oh VisFatigue isn't a visual effect
its
uh
worse
Vignette is though
yes it is used to show damage
Best coding practices would tell you to split these things up to minimize coupling
vis fatigue is separate from actual fatigue, so it can look like fatigue is going up but apply the change after so that the player doesn't drop below fatigue and stop sprinting
This is not even coupling, it's just a pot of stuff
it could be worse
I could have all the player things in this script
movement, inventory
That's actually smart
🥰
yaaay
in my first big project, I lumped ALLL the player things into the same script
health, movement, damage, attacks
it was just one script
oh god
Meanwhile my projects xD
You can use headers to better organize inspector
its split up a little bit
curlevel manager does footstep noises I believe
How did it get to this point?
yes it does
keeps track of them and plays them
this is just
how i tend to do things
wdym
curlevelmanager is a misnomer, all it does it get told the next level's footstep noise when you go thrrough a level transition, and then play that as the player walks
I thought I would use it for more but I ended up not
alright
It was being used for footstep effects like splashing and stuff but the splashes were too laggy so its no longer used for that
How do you handle the inventory between scenes?
wdym
keeping the data
its attatched to the player and I dontdestroyonload the player
Ah, so I'm guessing it's a singleton your UI then uses
???
Its probably very bad that i do not know what you are talking about
The generic approach seemed to have helped from what I can see on the profiler now, thanks for that btw
How does your UI get access to the player's inventory?
heres the script
please review and be apalled
Wait, is your UI attached to the player?
It's good to split up canvases at least
one for settings, one for inventory, and one for statbars
That's fine great, if you're hiding them the right way
I am
the worst thing about all this is the game runs perfectly fine
which is why I haven't seen the need to mess with stuff
If it works it works 😄
Well, good luck on your spagetti dish disguised as a Unity project
I will proceed to sleep
cool
Hi, how do I stop a client by the server with the client's ID in netcode?
Hi, i have to store in a file json format that is encrypted, which file type should i use? .txt or .json? what s the best and why?
NetworkManager.DisconnectClient(clientId);
if it is encrypted, then it will be a binary file. just use .sav or something
make up an extension
so .sav is the best?
you can name it whatever you want
it's not going to be something that the user can meaningfully use
@vestal turret Thank you, I will try it!
and where is the best place to store the key ? to encrypt?
if you have to ask that question, then I don't think you should be relying on encryption to protect anything
if the key is stored on the user's device, then the user can trivially decrypt and encrypt data at will
public class UnityEventAsset : ScriptableObject
{
protected readonly List<BaseUnityEventListener> Listeners = new();
public void RegisterListener(BaseUnityEventListener listener)
{
if (!Listeners.Contains(listener))
Listeners.Add(listener);
}
public void UnregisterListener(BaseUnityEventListener listener)
{
if (Listeners.Contains(listener))
Listeners.Remove(listener);
}
}```
```cs
public class UnityEventListener : BaseUnityEventListener
{
[Tooltip("Event raiser to listen to")]
public UnityEventAsset UnityEventAsset;
[Tooltip("Response to event raising")]
public UnityEvent Response;
private void OnEnable()
{
UnityEventAsset.UnregisterListener(this); // WORKAROUND
UnityEventAsset.RegisterListener(this);
}
private void OnDisable() => UnityEventAsset.UnregisterListener(this);
public void OnEventRaised() => Response.Invoke();
private void OnValidate()
{
if (UnityEventAsset != null)
UnityEventAsset.RegisterListener(this);
}
}```
I'm having a problem where when switching to PlayMode and Raising an event, it gives me a `MissingReferenceException: The object of type 'UnityEventListener' has been destroyed but you are still trying to access it.` when trying to access a listener in the list (they come as `null` after hitting play). The workaround is to, OnEnable, remove and add the listener. What's actually going on behind the scenes?
im getting a weird error every time my player touches an enemy can anyone help please
ArgumentException: GetComponent requires that the requested component 'Player' derives from MonoBehaviour or Component or is an interface.
UnityEngine.Component.GetComponent[T] () (at <4746c126b0b54f3b834845974d1a9190>:0)
PlayerHp.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/PlayerHp.cs:27)
Is multiple .Where() on List is less optimal than one .Where() with united cndidtion in terms of performance?
This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in C# or For Each in Visual Basic.
Is it mean that list condition will be gathered and executed only once?
Or multiple .Where() will stride multiple times through the list?
i believe each one will run the previous enumerator until it finds a value it can use
i would expect this to be worse than just using one large condition, still
i guess you could measure this by doing something goofy, like 100 consecutive wheres
i wan t to make that a bit harder not impossible but you know
Does anyone here have experience with Ink integration for unity? I'm trying to code a dialogue system and everything works fine except when after choosing a choice and it should jump back to the choices and show them again (everything works fine in the Inky editor), it doesn't show the choices when playing through the dialogue and nothing happens for "two steps", then the dialogue ends
Hello there, I assume this is sort of a newbie question, I have a parallel job where I am doing some calculations and right now I am refactoring my code to modify a struct value; The problem right now is that I have some conditionals on my job and in those I want to modify a value inside my struct at the current index, but for some reason the struct does not change at the specified index unless I call the function outside of those conditionals, what am I doing wrong?
//back
if (blockBack == 0)
{
//Does not work
AssignData(index, blockPos, BackFace);
}
//front
if (blockFront == 0)
{
//Does not work
AssignData(index, blockPos, FrontFace);
}
//Does work outside of conditions
AssignData(index, blockPos, BackFace);
private void AssignData (int index, half3 blockPos, NativeArray<half3> face)
{
_VertexData[index] = new VertexData
{
Position = AddQuad(blockPos, face),
index = index,
// Normal = _VertexData[index].Normal,
// Uv = velocityPosition.Uv,
// Tangent = velocityPosition.Tangent
};
}
30 wheres on 1kk list is 10 times slower than one where with 30 conditions.
It's not clear - likely an "obvious" issue with blockBack or blockFront not being what you expect them to be?
Hey, so can I use Resouces.Load in this situation?
Resources.Load("A\thisfile")
Resources.Load("B\thisfile")
where the filenames are the same but the path is different?
(I'm assuming _VertextData is a private [] that you're not mistakenly re-initializing or overwriting elsewhere, too)
yes but using / for the path delimiter
\t is tab
eg: A hisfile and B hisfile
thanks
I mean, the conditions do happen, I can debug them and they return true when there is a fron block or back block present, the issue I have is AssignData is not assigning a value at the specified index
It remains at 0 either at Position or Index
But when I take AssignData(index, blockPos, FrontFace); outside of the conditions, it does assign the value I expect
I have also placed a debug before doing _VertexData[index] = new VertexData and I do receive the input values
Hey there, I was wondering if anybody knows how I could use Text Mesh Pro with the Input System Rebinding sample. The only idea I have is to take the text from the regular text component and put it into a TextMeshPro UGUI component.
Text/TMP_Text are pretty much interchangeable in any way that would matter for that.
(other than just changing the type in the code and replacing the objects and references in any prefabs/scenes of course)
The reason I can't replace the text variables with TextMeshPro is something to do with this:
The new input system cannot yet feed text input into uGUI and TextMesh Pro input field components. This means that text input ATM is still picked up directly and internally from the Unity native runtime.
I have no clue what that means besides I can't change the text components.
where are you seeing that?
is the sample using UGUI, or is it using IMGUI?
also this is talking about input fields, not Text /TMP_Text
it's talking about where you "type" the new binding into
Here is where I found it: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/KnownLimitations.html
And here is the code snippet which I'd need to change to TMP but can't:
public Text actionLabel
{
get => m_ActionLabel;
set
{
m_ActionLabel = value;
UpdateActionLabel();
}
}
Change Text to TMP_Text (and add the appropriate using TMPro; directive
change it everywhere you see Text to TMP_Text
and change all the objects in the scene to TextMeshPro-UI objects
none of this has anything to do with input fields (which is what that known limitation is talking about)
:|
yes you need to change that variable (m_actionLabel) to TMP_Text too
as I said: #archived-code-general message
Maybe this is what I'm missing:
It was at the very bottom of the page and I didn't notice it.
the error here was telling you the variable was the wrong type. That's your cue to go to the variable declaration
Well, that fixed the problem! Wonder why everything I found told me it couldn't be done, besides one vague comment on a video where the creator said it couldn't be done.
no idea. The explanation you gave made no sense because the sample is clearly already using UGUI, and the text you linked said it can't use UGUI.
I'm trying to capture specifically a "rotational" input, with the example of Spin the input in a circle to simulate a fishing rod reel. Anyone got any ideas here? Or previous examples? I've been pondering this idea for a few days now. No idea where to even start.
capture rotational input from what device?
Mobile
So you mean a touchscreen?
Well yes, the input capture isn't as important, but the method I would handle capturing a continued rotation?
Are we talking about a virtual joystick, or are we talking about rotating your finger around the center of the screen, or what?
well it depends on the input device hence the question
I think for simplicity, a virtual joystick as that is what it currently uses
Hi I have an eventManager that keeps throwing a NullReferenceException and I'm not sure why
Event Manager Here:
{
// Bus Events
public Action OnBusTakeDamage;
public Action<float> BusTemperature;
public Action<float> BusHealth;
// Debris Events
public Action OnDebrisDestroyed;
public Action OnDebrisSpawned;
// Hero Events
public Action OnHeroShoot;
public Action OnHeroDash;
// Game Events
public Action OnGameStart;
public Action OnGameWon;
public Action OnGameOver;
public Action OnGamePaused;
protected override void Awake()
{
base.Awake();
}
}```
Inhereits from my Singleton Abstract Class
```// A static instance is similar to a singleton but does not destroy any new instances,
// Instead overwriting the current existing instance.
// Good for resetting states.
public abstract class StaticInstance<T> : MonoBehaviour where T : MonoBehaviour
{
public static T Instance { get; private set; }
protected virtual void Awake() => Instance = this as T;
protected virtual void OnApplicationQuit()
{
Instance = null;
Destroy(gameObject);
}
}
// A Basic Singleton. Will destroy any new instances created.
public abstract class Singleton<T> : StaticInstance<T> where T : MonoBehaviour
{
protected override void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
base.Awake();
}
}```
NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () (at Assets/_Scripts/Managers/GameManager.cs:32)
```private void Start()
{
EventManager.Instance.OnGameStart.Invoke(); // THIS IS LINE 32
SetValues();
fallHeight = Vector3.Distance(startTrasform.position, endTransform.position);
currentHeight = fallHeight;
}```
then all you need really is to store the input vector from the previous frame. Every frame you can then calculate the signed angle difference between the two input vectors and get an angle amount that changed
you'd have to share your full error message and show us the line of code that it's referring to
Got it, compare angle differences. Ty!
basically just using this:
https://docs.unity3d.com/ScriptReference/Vector2.SignedAngle.html
like cs float angleDiff = Vector2.SignedAngle(previousInputVector, currentInputVector);
and of course if you want to know the rate per second it'd be:
float angleDiff = Vector2.SignedAngle(previousInputVector, currentInputVector);
float rotationRate = angleDiff / Time.deltaTime; // in degrees per second
so you'd either accumulate these angle difference over time or look at the rate of change.. It depends what you're looking for
I believe the rate of change is what I'm after, as that will correspond with a counter.
Fiexed it Error code at the bottom along with the method triggering it
right but it was not clear which file was GameManager.cs and which line 32 was
Can Coroutines be used in a static non-MonoBehaviour script
StartCoroutine can only be called on a MonoBehaviour instance. The place where the IEnumerator function actually lives can be anywhere
IEnumerators not Coroutines
Commented which one it is is that better?
If nothing is subscribed to an action, it will be null - so someAction.Invoke() will throw an NRE
yes. Either EventManager.Instance was null, or there were no listeners assigned to the event
you can do EventManager.Instance.OnGameStart?.Invoke(); to safely invoke it
assuming it was the no listeners thing
Not at the moment no. Thanks for the solution
@leaden ice @wide terrace Thanks that fixed it I totally forgot about checking for null
What is the best way to manage ui events like button onClicks?
Dragging files in unity events seems very tedious and unreliable.
With GetComponenting buttons from script of the same object it is impossible to subscribe for multiple butttons
you can add subscribers from code if you really want with AddListener
I prefer to assign the listeners in the editor whenever possible
By adding scripts to every button and doing GetComponent for button?
not sure what the GetComponent is needed for
I using it to get the button I want subscribe to like this:
Button _button;
void Awake()
{
_button = GetComponent<Button>();
}
void OnEnable()
{
_button.onClick.AddListener(StartGame);
}
Is there is a better way?
there would be no point in doing that since you can just assign StartGame to the button from the inspector
but sure you could do that
Then what you meant by "you can add subscribers from code if you really want with AddListener"?
Dragging scripts into unity events seems unreliable and I wonder if it would be better to subscribe to events in code
there's nothing unreliable about using the inspector
the most common case for adding subscribers in code is when you're instantiating button prefabs and want to add a listener from the instantiating script to the button instances
So the best ptractice for managing ui events for static elements is configuring them through inspectpor like this?
I would say so, yes.
it keeps your code hierarchy-agnostic
which allows more code reuse
But it breaks if I simply rename my function
sure and the other way breaks if you simply rearrange your hierarchy
Hierarchy? I attached script to the button it subscribes to.
If I'm draging script from folder to event field, there is no functions to select.
Yes, the hierarchy
the arrangement of GameObjects and their components
if you, say, move the script to a different object, or move the Button component to a different object, it breaks
But I can Require the button component, right?
Sure
Which, again, locks you into a particular hiararchy configuration
if you're fine with that then go for it
Ok, thanks
hey! i was wondering if someone could help me with a maths related coding problem?
im trying to spread out a hand of card gameobjects in unity, like in the pic, but cant seem to find much help online, and am unable to nudge chatgpt into providing a workable answer
maybe you could do some circle related magic? youd position a card on the circles edge depending on your hand size / its location in hand, and have its transform.up equal to the normal of the edge at that cards position, giving you both the rotational and y-positional effect in one swoop? as a non mathsy person ive got no idea where to even begin with this though
in case it helps at all the second pic is my current solution to positioning the cards on their x axis. thanks :)
Firstly, choose a point below the screen that will be your circle center. Then choose the radius of the circle.
You can find Y position of a card like this: Y = sqrt(radius^2 - X^2), where X is the position you are calculating on the screenshot.
After that you can find rotation of the card with Quaternion.LookRotation(circleCenter - transform.position)
tyty ill give that a try now
Hey there again, I'm having a problem with the Input System rebinding where it only works in one scene and not in any others. I'm not sure what the problem could be, but it happens with the actual key rebinding since every type of rebinding script I used had this problem.
sooo my first attempt isnt going super well lol
i might be able to fix that actually 1 sec
Seems like you should rotate cards vertically
so now as i add more cards they move downwards and to the right lol (also the rotations gone)
quaternions arent my strong suit
to get a "spread" like that, you want stack all of the cards on top of each other, then use transform.RotateAround to rotate them slightly around a far-away position
that'll get the arc shape
So question on Unity serialization and nested classes. I have a component with an instance of a class that has its own class as a variable. Only the top level instance of the class is showing in inspector. How would I have it so I can have it serialize another step down at will?
Not sure I quite follow but I have done what I believe is something similar.. got code? Might be able to help with it if I know exactly what you're doing.
Hi
[Serializable]
public class IsAHasA {
public int value;
[SerializeField]
public IsAHasA next;
}
value is showing up, but not next
Also getting this in logs XD
Serialization depth limit 10 exceeded at 'IsAHasA.next'. There may be an object composition cycle in one or more of your serialized classes.
Ah yea I've never done that and I can't imagine that's even possible... I'm assuming the depth limit is caused by the fact that each instance of IsAHasA contains another IsAHasA, creating a memory leak maybe?
If I make next an array I can get one more layer, but it is cutting it off pre-emptavly.
Not memory leak, just infinite creation as Unity auto generates variables.
I thought array would work(which it does once), as Unity doesn't auto generate values there
What do you mean unity "auto generates variables"? infinite creation should be your big red flag that it's a big no no.
Wrong channel
So in actualy C# programing a pattern like the above is common place, like with chained nodes, but there you have to assign a value to the class varaibles. Unity auto assigns values to public class variables. It doesn't do this with class array variables. Yes infinite recursion is bad, but a fault of Unity not of bad coding practices.
Hi, this is how my FBX object looks in the editor. How can I create a reference field in which I can put the root object, instead of specifically to the mesh and only the mesh? I'd love to have the reference to the mesh and the materials in one go
reference the mesh renderer
it has acess to all that
if you want the mesh itself you do need mesh filter
yea but I need specifically the reference to the file, because I'm swapping the mesh and the materials on it, with a script.
And that script needs references to all that.
I should be more precise: this isn't hierarchy window, this is the Project window. I need to reference the object in the project window. Not some mesh renderer that has this mesh and materials attached.
maybe resource folder?
No, I need to make a field in the inspector on a gameobject, where I can drag this root object
I'm asking what type the field should be - if I do a mesh field in my script, I can drag the mesh itself, not the root object that holds the mesh and the materials
GameObject
Thanks, I can assign it now. But I'm confused, how can I get the mesh and material now, from that gameobject? Does that gameobject have a mesh filter now, or something?
getcomponent through the gameobject
I recommend you just make a prefab that has all that setup already
I can't. I'm swapping a mesh on an object that is already a reference in other scripts, and I don't want to mess with those because they're from the asset store, and there's a ton of them.
I just need to randomize a couple of meshes on objects like that.
if I destroy and recreate that object, those references would become null. If I disable/enable objects, those scripts won't work. Hence I need to alter the mesh filter on those objects directly.
Working on a 3D game with a ton of hand placed enemies. To help with hand placement, I want to be able to see the various enemy models standing where I placed them in scene view. So simply dragging enemy prefabs in would be nice. But because there are so many, I think it will be important to pool and spawn them. So I can't just drop prefabs in. Any advice on this issue?
I have two ideas. Either I make a spawner that uses graphics.draw to preview what I placed, or I can place prefabs in and they can zorch themselves and leave behind spawn points when the game starts. Neither sound that great, so I'd appreciate some outside perspective.
I'm looking for some insight or resources about world state systems and how they implement catching up a default state to a desired state.
https://docs.unity3d.com/ScriptReference/SerializeReference.html might work better.
I use a state system for my turn based battle game (I can provide a steam/google link if you want). Basically there's a state object that has the "true" state, and a list of battle actions that modify the state as the turns come in over the network. There's also some pretty deep equality checking and the ability for the server to send the "post" state in addition to all the change events for debugging help.
Any time a new turn comes in, I also copy the "true" state into a before state that can be modified by the turns slowly (ie, to allow animations to happen and not need to worry about things like showing the hit points before the attack has finished).
Not sure what specifically you're looking for, but hopefully that's useful?
It it, i think the bit im missing out on is a state having entry and exit data, which is closer to a state machine than my simpler style of just a dictionary of state names and a boolean if its done
https://paste.ofcode.org/zn8wz4aJp9PY3bSkvw7sh4
In my game, dots instantiate on a screen, and you have to click them in the order they came in and avoid clicking the bad dots.
Problem: The error is in the randomizeArray() function which randomizes the "dots" array to ensure that the dots instantiate in a random order. It's saying that the dots[i].name is invalid for some reason
what is the actual error you are receiving
well those line numbers don't line up with the code you've shown. but a null reference exception means that the entry in the array is likely null if it isn't throwing when you access the Length property of the array
the error is thrown on line 255
just breezed on past the rest of that message that told you the issue then, eh?
the content of the array are dots(sprites) that are not in the scene. I instantiate those dots in the scene, and then destroy them whenever the user presses on the dots .
seems like one or more of your colored dots variables are not set in the inspector. also why not just populate the array directly in the inspector instead of these separate variables?
i also feel like i've given you this advice before . . .
Seems like you simply haven't assigned those colored dots variables. Unclear to me why those variables even exist
also looking back, it seemed you previously had more than one copy of the component in the scene which caused a similar issue. make sure that isn't the case again.
the variables are set in the inspector
pretty sure you said that last time
its not this time
take that code i gave you last time and add it in again and show me what it prints. again.
ok
actually wait, let me modify it a bit real quick to make it nice and obvious for you
for(var i = 0; i < dots.Length; i++)
{
Debug.Assert(dots[i] != null, $"Array entry is null at index {i} on {name} - {GetInstanceID()}", gameObject);
}
put this in Start before you call that randomize method or even at the beginning of the randomize method, either option is fine
Perfect thanks!
nothing is being printed out
Add a log before the loop and print the length
show the updated code and the updated error message(s) you receive so that i can see the actual current line numbers
do you perhaps have some extra line of code somewhere (or even a blank line) in your code editor that is not being included in the code you pasted in the site? because it seems your line numbers are off by 1 from what you indicated before. also please use the updated code that i provided that will print the name and instance ID of the object.
you should also move it directly above that loop where your error is happening
Presumably you destroy some "bad dots" and then keep trying to use them, causing an NRE when you read the name.
yes that is what is happening, the bad dots are the ones that are null in the List
even though Destroy the "bad dots", they still appear on screen for some reason
the array is filled with the prefabs not the instances that were spawned in the scene. you don't even bother storing references to the instantiated objects
ah that make sense than k you
man. trying to make an fps controller is making me feel extremely stupid
i'm on the verge of just following some shitty yt tutorial since doing it myself is just resulting in headaches
Anyone familiar with the new Splines know how to get the nearest point on the spline itself based on a certain position? Not sure what I'm doing wrong
As you see from video, the Utility function they provide does seem to follow the spline but the offset seems really off?
btw their function is using float3 from UnityMathematics
Here is the utility function I'm using
https://docs.unity3d.com/Packages/com.unity.splines@2.2/api/UnityEngine.Splines.SplineUtility.html
My code
void Update()
{
SplineUtility.GetNearestPoint(spline.Spline, transform.position, out float3 xyz, out float t, 3,2);
nearestPoint = new Vector3(xyz.x, xyz.y, xyz.z);
Debug.Log($"x: {xyz.x} y: {xyz.y} z: {xyz.z}"); Debug.Log("t: " + t);
}
private void OnDrawGizmos()
{
if (Application.isPlaying)
{
Gizmos.color = colorDebug;
Gizmos.DrawSphere(nearestPoint, 0.2f);
}
}
is there any easy way to find all gameobjects in an area? ( not colliders, gameobjects whose origin is inside said area )
I'm unsure exactly what your setup is, but I imagine the problem is that the spline is not in the space you think it is, and you will need to transform transform.position into the space of the spline, and convert the xyz coordinates back to world to display them.
I was thinking this as well, I just tried looking for any methods already included that might do this, just not sure where to look anymore tbh.
The Utility class I've linked , I thought would do the trick but got close to something but no cigar.. was hoping someone might know a way, googling proving no answers on this.
transform.TransformPoint and transform.InverseTransformPoint
I will try this, would this go on the In V3 or the xyz result
splineTransform.InverseTransformPoint(worldSpacePoint) // get the query point in local space of the spline, used in SplineUtility.GetNearestPoint
splineTransform.TransformPoint(result) // get the result in world-space.
You are a life saver my friend! thank youuu!
I have a slight problem, I have a scriptable object that displays text, and the PC's name on top of the text box.
Is there a way to, on a mouseclick on the scriptble object, cause the UI textbox to pop up and the text to play, then close the window?
The scriptable object and the script (latter)
ScriptableObjects are just assets or in memory. They can neither display anything nor be clicked on.
Now GameObjects and their components? That's a different story.
Look into IPointerClickHandler or the EventTrigger component
thanks
Also, are there any tutorials on developing a save point system?
Where you can only save on the correct savepoint?
Are you supposed to be able to just remember how your code works, even as it gets larger and larger? I find myself having to reread my own code to remember function names etc all the time
I dont even remember what scripts I have sometimes, itd be a miracle if I remembered what functions it has. You're supposed to write readable code and use comments for this exact reason.
Been suffering from 2 days while trying to make jump buffer and Hold jump to jump higher work together... But it doesn't.
What a pain
Trying to get jump similar in Hollow Knight
hi. i’m trying to conceptually break down the fundamental requirements for a fps controller instead of just throwing it together. i would appreciate if anyone could point out any glaring flaws in my logic here :3
-gravity - subtract from the character collider’s y velocity (applied in world space) up to a limit (terminal velocity)
-ground check - cast a short ray from the bottom of the capsule to slightly below it. this should hopefully mean it can tell when it is grounded. when grounded, set y velocity to -1 so it stays on the ground
-velocity - have this be a vector2 that’s applied in local space to the transform’s x and z components in FixedUpdate (y vel is separate since it should be applied in world space i think.)
-velocity decay - on the ground your velocity should decrease quickly (possibly exponentially according to your speed) which would serve as a movement speed cap
-input - saved in Update and added to the player’s velocity in FixedUpdate to ensure it gets processed asap
-jump - if grounded, set y velocity to 10 and give a small window where y velocitu cannot be set to 0 (seems to not let you jump and overrides the jump velocity otherwise)
wall and ground collisions seem to be handled by the character collider so i think that should be everything i need :)
this has been giving me headaches for a while so i decided to step back and consider it as a whole
good luck, i love the way hk controls :)
COMMENT EVERYTHING.
As you get more comfortable, patterns emerge that make it easier to keep track of more of what's going on. You can also learn to write code in a manner that is easier to understand when you read it again.
Commenting is also useful but ideally should convey intent or explain architectural decisions rather than describe what each line of code is doing. The code can speak for itself if you write it to be easy to read.
how can i get the real rotation of an object?
( say his parent is rotated to 30, the object itself is -10 then i want 20)
That is .rotation
.rotation is the global rotation
oh cool, thought it's relative
localRotation is the local rotation
thanks1
Np
hey, can you read the tEXt chunk of a png file at runtime?
why wouldn't you? the file format is pretty straightforward
Hello!
I generated a mesh with square faces (like in Minecraft) at runtime.
The mesh has a mesh collider and the player has a mesh collider and a cylinder mesh.
My problem is when I walk against walls, it does something weird, as if the player was slightly going inside the collider and then getting expelled.
I'm quite new to 3D and physics in Unity so I have no idea what could be causing this and how to fix it 😦
I also tried with a box collider for the player and it was even worse : the player was getting stuck when walking against walls.
there are a couple of causes that can be the reason for your problem. Since i don't have enough info to help you i'll list some of them:
- Your player's collider may be uneven.
- your movement system needs an overhaul - this may be the real cause behind your player getting stuck on box colliders
- you are trying to push yourself into the geometry, which causes unity to pull you back (movement system again)
- you are using physics based movement and didn't account for friction
Thank you!
For the movements I set the rigidbody velocity so the player is "pushed" into the walls I guess, could this be the problem?
private void FixedUpdate()
{
float x = 0;
float z = 0;
if (Input.GetKey(KeyCode.W)) z += 1;
if (Input.GetKey(KeyCode.A)) x -= 1;
if (Input.GetKey(KeyCode.S)) z -= 1;
if (Input.GetKey(KeyCode.D)) x += 1;
rb.velocity = z * 8 * transform.forward + x * 8 * transform.right;
}
But I don't really see what else to do, shouldn't the collision system prevent any movement into the wall (instead of allowing it and then pushing the player back) 🤔
Also I set friction to 0 for both colliders
And for the player collider I simply used the default cylinder mesh and a mesh collider
the main problem is that you're setting the velocity and then entrusting unity to handle the rest, this will cause some major problems, especially later on when you want to implement slopes.
My suggestion is that you take a look at a couple of open source movement systems to learn from them. As to why this is happening. In unity's eyes, you clipped into a wall with a specific vector, after a physics update. It pushes you back to where you should've impacted the wall, in box collider, it happens to be where you were but slightly forward (resulting in you almost staying in place). For mesh collider, since it isn't a perfect wall, you get the bouncing motion.
As for a quick fix, you should check first if you're going to clip a wall, and if yes. You should cancel that vector.
Alright thank you! 🙂
But basically that's the same as recreating a collision system 😭
i have an UI Image (a world map). I want to move another object when the player moves through the world.
I have a relative world spaced position to the top left corner of the map, but as the UI anchor coordinates aren't translating to world coordinates 1:1 I somehow need to calculate a conversion ratio. I have no idea how though... I tried using referencePixelsPerUnit along with the images pixels per unit, but its still off
currently doing:
var camPos = (Vector2) UnityEngine.Camera.main!.transform.position;
_rectTransform.anchoredPosition = (camPos - _mapCorner) * (canvas.referencePixelsPerUnit/pixelsPerUnit);
Hey, hope y'all are doing great. I got a problem that I am struggling to come up with an approach to.
So basically, I am making a strategy game where the player will be controlling their pawns from above and there will be these NPCs that will fundamentally do the same things involving combat. Most of these are irrelevent though. So I am trying to come up with a system that can give me points in my procedurally generated map that are good points to take cover in a combat. (mostly props stitched together. So not a procedural terrain.) In the case of the player's pawns, I just want them to check if their current position is a cover to play a specific animation and maybe crouch. But for the NPCs, I will need to find these points from scratch and send them there.
So I came up with several approaches that didn't exactly satisfy my needs so I did a little research and saw this video: https://www.youtube.com/watch?v=t9e2XBQY4Og
This is exactly what I need but unfortunately I am using the AStar Path-Finding Project (https://arongranberg.com/astar/) and to be honest, I didn't really understand how this approach fundamentally works. I tried going over the code, watching the video at 0.5x. But no, I do not seem to understand, I don't know if I just lack some key information here or if the video is actually hard to understand but when I tried to slowly review the code myself and just get how it works then do it myself a little differently, I still don't understand much because of the lack of documentation.
Has anyone tried achieving something like this or knows the fundamentals of a system like this? I have several years of experience so not a total beginner but there are just some things that I don't get about this. I just need the fundamentals of this then I'll code it myself to fit my case.
Thanks a lot!
Learn how to make NavMeshAgents find valid cover spots from another target object. In this video we'll specifically use a Player, but this can be applied to hide from any object - a grenade for example. Together we'll create a configurable script that allows us to refine which objects are valid to hide behind, and exclude those that are not.
W...
@waxen spruce !collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
I spawn Player in Awake. Objects that are dependent from player initialising in Awake too. Like:
public void Awake()
{
_weaponsController = ReferenceManager.Player.GetComponent<PlayerWeaponsController>();
}
I can't do this initialisation in start, because I have events I want subscribe to in OnEnable:
public void OnEnable()
{
_weaponsController.onWeaponChange += HandleWeaponChange;
}
So I'm getting null reference errors because some objects trying to access player before it is spawn.
How can I resolve this issue?
I can move initialisation to start, move subscriptions to start with the check for enabled and isSubscribedForX flag. And then add another subscription in Enable that checks for null on target and checks isSubscribedForX before subscription.
But I'm sure there is a better solution for such common flow.
that is the solution you are not supposed to use Awake for accessing external objects
oh okie cool
Awake/Start are not just methods they are part of phased initialization, first phase will call Awake on all objects, second phase will call Start
within a phase there is no guarantee of order
unless you fiddle with SEO
Ok. So I have external object with event I want subscribe to. And I want to subscribe to it in onEnable. What is the common practice for such cases?
OnEnable happens after awake right before Start, should be fine
So I need move initialisation and subscription to onEnabled and also add check to not initialise multiple times if object would be enabled again?
pretty much
i did
i simply set the destination of my ai (im talking about enemies) based on the agro
i do agro by a radius check
you can move your ReferenceManager higher in SEO
and i block the radius on the point it detects collision with anything rather than player
but it means from now on you are relying on manually setting your whole architecture in SEO and maintaining it there
and if i block for an estimate amount of time the enemy losses me
@peak halo hopefully i helped
i didn't neceserally played with the A* i played with the way it gets it's targets
What is SEO?
Thanks. I'll try to avoid that and change where I am accessing objects.
I am having an issue, wherin I have a Canvas that holds a game over screen, and is disabled by default. It has a button that reloads the scene. However, afterwards when the screen is needed a second time, it just throws a MissingReferenceException instead. I have looked around the internet, and the solution I found there was to mark it as DontDestroyOnLoad - but when I did that, the Canvas got duplicated on Scene Reload (and is not hidden). Is there a way to fix this?
The class responsible for showing the Canvas:
public class GameEndBehavior : MonoBehaviour
{
[SerializeField] private Canvas gameEndCanvas;
void Start()
{
PlayerHealthBehavior.OnPlayerDeath += OnPlayerDeath;
DontDestroyOnLoad(gameEndCanvas);
Utils.SetVisibilityRecursivly(gameEndCanvas.transform,false);
}
private void OnPlayerDeath()
{
Utils.SetVisibilityRecursivly(gameEndCanvas.transform,true);
}
public void OnGameRetry()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}```
PlayerHealthBehavior:
```csharp
public class PlayerHealthBehavior : HealthBehavior
{
public delegate void PlayerDeath();
public static event PlayerDeath OnPlayerDeath;
public override void OnDeath()
{
Utils.SetVisibilityRecursivly(transform,false);
OnPlayerDeath?.Invoke();
}
}```
Utils:
```csharp
public static void SetVisibilityRecursivly(Transform transform, bool visible)
{
foreach (Transform child in transform) SetVisibilityRecursivly(child, visible);
transform.gameObject.SetActive(visible);
}```
Q: how expensive are unity’s collision checks? Does the CPU time scale quadratically with the total colliders in scene at once? Or is unity smarter than that?
it scales with amount of colliders being solved in groups of colliders touching, called islands
100 rigidbodies piled up will result in combinatorial explosion for the solver
100 in sleep state far apart wont participate in any solving at all
interesting. is there an article in documentation or something?
physx docs
could you help guide me a bit more to the right spot? googling unity physx just sends me to a bunch of wrong places
is it in the normal documentation database?
so PhysX is not a Unity/C# thing, but a system thing?
gotcha
you use components as a intermediate interface
Thanks, though I didn't exactly get it, what is an agro? Can you elaborate a little on how the system works overall?
I will read that document to educate myself. ty for helping
It's much smarter than that.
Look up OctTrees
And KD trees
And BVH
It's using some or all of these optimizations
ok. also if I understand cache’s explanation, let’s say I have a tilemap. That tilemap has a bunch of masses of ground tiles in one layer.
- Composite collider groups areas.
- Every tile gets a separate box collider (very dumb).
If I understand properly, Unity will not take a performance hit by switching from 1 to 2. Is this accurate?
if a raycast is spawned inside of a collider will it return that collider as well
static non moving colliders should only impact memory
rigidbodies are what impact performance, when 2+ rigidbodies touch they form a local group which is using a solver to resolve collisions
Not accurate. There's a tradeoff of memory and it's more complicated than just a or b
The distribution of boxes and objects that might collide with them may also be relevant
I’m assuming memory is free. Just thinking about CPU time
the more rigidbodies are interacting within that group the bigger the perfromance impact, depending on how much time it takes the solver to stabilize the whole group
so if you have a tall box filled with spheres which is near impossible to stabilize you will bring your game to a crawl
and there yes it grows non linearly
ye, i create an overlap sphere as a radius and detect each collider it collides with
so if I understand properly, CPU time needed scales with (rigidbodies)^2
I think that you might not understand how the SamplePosition actually works. When you sample a position on the NavMesh, it tries to find the closest "Valid" position. Then we check if the position is actually hiding the player. If not, then we try the opposite (Resample the position but with an offset).
furthermore i can get the object itself as a transform, rb and it's tag
i cant say exact complexity, i dont think it is clearly defined
if it's let's say an obstacle i prevent the radius detecting past it and in it
well, let’s say I have a jar of jelly beans, like you described. The cost of the jar would be more like ~rigidbody^2 in the jar, and not ~collider^2 in the jar
so if I had a jar of jelly beans and all the beans are colliders, then we are totally ok. But slowly changing jelly beans to rigid bodies is what will quickly raise the cost.
Would that be accurate?
If you have no rigidbody, there is nothing to calculate.
yes, static moving colliders also have a small cost but if its static its one less object for the solver to iterate on
they still produce contacts but for the rigidbodies
So can you change the texture of an HDRP material in unity with C# ?
its working for normal material
yes
can i show my code and ask for what am doing wrong then @rigid island ?
have i been more exact?
i used the term agro because i specifed that i do this for my enemies
Follow up question: Let’s say we have a jar of jellybeans. Every bean is a rigidbody with 1 sphere collider.
Would giving every jelly bean a second sphere collider quadruple the total cost per frame?
using UnityEditor;
using UnityEngine;
using System.IO;
public class AssetDatabaseExamplesTest : MonoBehaviour
{
[MenuItem("AssetDatabase/printmat")]
static void SubFolderExample()
{
var folders = AssetDatabase.GetSubFolders("Assets/Silex-Materials_Pack/Textures");
string foldvar = folders[3];
string[] files = Directory.GetFiles(foldvar+"/", "*.png", SearchOption.TopDirectoryOnly);
string wellyay = files[0];
string materialPath = "Assets/Silex-Materials_Pack/Materials/test/Mat_test.mat";
string texturetest = "Assets/Test/bltest-1.png";
Texture2D extexture = (Texture2D)AssetDatabase.LoadAssetAtPath(texturetest, typeof(Texture2D));
// Debug.Log(extexture);
Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
// Debug.Log(material);
material.SetTexture("_MainTex", extexture);
// Debug.Log(extexture);
EditorUtility.SetDirty(material);
// AssetDatabase.GetAllAssetPaths()
}
}
since my NPCS are literally just talking statues or walking from point A to point B rarely
material.GetTexture("_MainTex"); did return the proper value
also Texture2D extextur is returning the proper value
but material.SetTexture("_MainTex", extexture); is not returning or showing any error also not working
note for non HDRP material it did work
and if unity version matter its 2020
probably not, it depends on how many contacts were produced, both single and 2 spheres can produce roughly the same amount of contacts, but what can affect performance the most is the shape,
think of it as the classic fitting problem, how many things you can fit in an enclosed space, when you do that example you are asking the solver to resolve this, and it can result in a very long or infinite amount of work,
every iteration every object in the jar is offset by a little, in an attempt to separate them, in case of a single sphere it can be relatively easy, in case of 2 the amount of possible positions they can be in can become astronomical
so its not about the amount of colliders its about the shape
problem also arises from the iterative nature of it, for example solver does 5 iterations in an attempt to move the object away from any contacts, since the object is sandwiched between bunch of others, it still ends up overlapping, so it has to be processed again next frame
object will stop being processed when its found a stable position, it switches into sleep mode
I see. So if the jar of jellybeans is left completely undisturbed, and if the solver ever gets the beans to all have zero speed, then framerate will go back up
But if the shape sucks, that second “if” is unlikely to happen (quickly if ever)
possibly, there can be some fallback code that breaks out of it even if its not solved
ty for taking time to explain. I think I get it now. I will read more of that documentation to learn
I have:
void Awake()
{
Debug.Log("spawn");
}
And in another component:
public void OnEnable()
{
Debug.Log("access");
}
Both components exist in the scene, they are not spawn after game start.
Logs looking like this:
Why Awake is called later then onEnable?
See https://docs.unity3d.com/Manual/ExecutionOrder.html
Awake and OnEnable are called on all object at first. A.Awake, A.OnEnable, B.Awake, B.OnEnable...
You might want to use Start instead of OnEnable.
You can also alter the script order with https://docs.unity3d.com/Manual/class-MonoManager.html
However, this is not good practice
You should make your dependence explicit and not implicit.
Yeah, it working that way, but I don't really want to do it like that.
I have object with event I want subscribe to. Ti di this I need to do GetComponent. And I want to subscribe to it in onEnable. What is the common practice for such cases?
You should have explicit reference to the object through an interface or use an intermediate object (Singleton or ServiceLocator or any other pattern) in between that synchronize them.
It kinda hard to know what is the best in your situation as there is multiple factor.
Where I can check more on "explicit reference to the object through an interface"?
[SerializeField] is an explicit reference to a UnityObject.
You can also get an explicit reference through a Singleton. MyObject.Instance
Basically I have UI that getComponenting character health, but the character is spawn when the scene starts and there is different characters that can be spawn.
In this situation, you better have an intermediate object such as a Channel and an object that contains all the player instead of using the Observer Pattern.
When the UI is created, you query the current available player.
When a player is created, it notifies the channel which the UI is subscribed to.
It requires something to hold the current player.
That can be a static (Which is not recommanded) or a GameManager script of the sort.
Why static classes for such things is not recommended?
Because static gives far less control
For example, there is no way to pass dependencies to static methods
It is usually not recommended because it has less flexibility.
A better way to create a "static" context is to make a singleton
Thanks
So I need to subscribe to GameManager event in onEnable of the UI components and then call the method which will invoke the event in Start?
I can't invoke event immediately when the player spawns because it can happen before ui components subscibe to this event, right?
i am trying to make leaning like in rainbow six siege and it works kinda but when i rotate the camera it leans in to wrong places and has the wrong rotation. can someone pls help
private void Awake()
{
motor = GetComponent<PlayerMotor>();
onFoot = new PlayerInput().OnFoot;
headPosition = camHolder.transform.localPosition;
}
private void Update()
{
//Debug.Log(isFreeLook);
camYRot = cam.transform.localRotation.y;
cam.transform.position = camHolder.transform.position;
}
public void LeanStop()
{
leanAngle = 0f;
isLeaning = false;
leanDistance = 0f;
Debug.Log(isLeaning);
}
public void LeanLeft()
{
leanAngle = maxLeanRotation;
leanDistance = -maxLeanDistance;
isLeaning = true;
Debug.Log(isLeaning);
}
public void LeanRight()
{
leanAngle = -maxLeanRotation;
leanDistance = maxLeanDistance;
isLeaning = true;
Debug.Log(isLeaning);
}
public void ProcessLean()
{
if(isLeaning)
{
Quaternion leanRotation = Quaternion.Euler(cam.transform.localRotation.eulerAngles.x,cam.transform.localRotation.eulerAngles.y,leanAngle);
cam.transform.localRotation = Quaternion.Lerp(cam.transform.localRotation,leanRotation,leanTime);
Vector3 cameraOffset = cam.transform.right * leanDistance;
Vector3 adjustedCameraOffset = Quaternion.Euler(0f,player.transform.eulerAngles.y,0f) * cameraOffset;
Vector3 targetPosition = headPosition + adjustedCameraOffset;
camHolder.transform.localPosition = Vector3.Lerp(camHolder.transform.localPosition,targetPosition,leanTime);
}
else
{
Quaternion leanRotation = Quaternion.Euler(cam.transform.localRotation.eulerAngles.x,cam.transform.localRotation.eulerAngles.y,0f);
cam.transform.localRotation = Quaternion.Lerp(cam.transform.localRotation,leanRotation,leanTime);
camHolder.transform.localPosition = Vector3.Lerp(camHolder.transform.localPosition,headPosition,leanTime);
}
}
camYRot = cam.transform.localRotation.y;```
Did you mean `localEulerAngles` here?
@rigid island hey i dont wanna take much of your time but you said yeas about changing HDRP with unity i found out in the docs there is HDMaterial unity 2020 didnt recognize it, can you point out for me what am missing ?
btw i shared the old code above
is there a event that fires after Start?
what are you trying to accomplish?
I need to build a node graph (for a perk system) - and to build the graph I need to be sure all nodes exist, so I wanted to create a seperate class handling all the graph building, but that would need to happen after the rest of the nodes all exist - hence me looking for something after start. (The nodes would be already in the scene, and no new nodes would come to exist while running).
Create the nodes in Awake (which runs before Start)
build the graph in Start
or do this somewhre
void Start() {
CreateNodes();
BuildGraph();
}```
no I mean cam.transform.localRotation.y it was for debuging its not used in the leaning functions.
it's a meaningless number
it's part of a quaternion
That could work, Ill see - ty!
not the rotation around the y axis
it was for debugging a outer future i don't use that number anymore but thanks.
Yo! Trying to store my spline data somehow so it's reachable within jobs. Is there any easy way to do that? I just want to evaluate a point along the spline to set a position
Thanks! How efficent is that though? Isn't there a way to do this with better accuracy?
Whenever I've done this I've converted the spline into an array of Matrix4x4s equidistant along the spline then you just linearly interpolate between the two closest ones inside the job to sample it
Does not seem to be the most reliable way of finding hiding spot.
Ah so no way to use the built in methods? So basically the spline is not compatible with ecs unless I do my own implementation?
Yeah I also felt like it. You know any better ways?
I think so - since it uses a lot of managed objects
Assuming you're talking about Unity's spline package
Yeah Unitys package. Damn. Thank you for the answer! ⭐ 👍
potentially if you use this maybe it's workable since it's all structs? https://docs.unity3d.com/Packages/com.unity.splines@2.0/api/UnityEngine.Splines.Spline.html#UnityEngine_Splines_Spline_CopyTo_UnityEngine_Splines_BezierKnot___System_Int32_
Not sure if that's blittable or not
or how easy to sample that is
I've always just found it easier to use the M4x4s
Yea not really I still don't understand what an agro is. Thanks for your efforts though really appreciated
I hope its not too early bring this down, but does anyone have suggestions regarding this problem?
I was able to save the BezierKnots in a blob to construct my spline as a NativeSpline 🙂
Basically, normally when you load a scene all the stuff in the old one is destroyed.
What "DontDestroyOnLoad" does is it prevents it from being destroyed, so you end up with a double since you are loading the same scene and not destroying the version you had in the old one.
You could use a singleton pattern to prevent the double.
I think there might be something funky going on with the statics here?
Static variables and methods are shared between all instances of the same class so maybe something stays from the "old" scene and doesn't get updated for the new one.
Or it could be a timing issue.
Maybe something is trying to get a reference from it while it's still disabled.
I would have expected DontDetroyOnLoad to be smart enough to stop the duping issue - welp.
How would a singleton prevent this problem?
The static stuff - how would I transfer an event without having it static?
Singleton pattern is basically just a system that makes sure you only ever have 1 copy of something in a scene.
I like throwing it on things liek music players along with Don'tDestroyOnLoad to keep music playing between scenes without having duplicate music players.
I'm not entirely sure if it has some weird interactions with events though.
most likely you are just not clearing events
consequtive invocation raises dangling delegate referencing dead object
so, when I load the screen, I unsubscribe from the event?
anyone knows a vs code extension that automatically generates documentation like this?
i hate xml documentation
welp, that did the trick - thank you very much!
.cache knows way more about code stuff than I do, he's probably right. I dunno that much about events, but seems you have static events yea.
similar to googledoc in python
Well the xml doc is there for a reason. IDEs and text editors with intellisense support use it to actually give you information when you hover over something, or when going through quick actions. Not using it is very weird.
the image i linked is from unity's own docs, and vs-code handles it pretty well
@night sparrow like this? https://marketplace.visualstudio.com/items?itemName=cschlosser.doxdocgen
yeah, but for c#. This extention works for c and cpp
hm doxygen supports c# out of the box
Is there a way to use OnButtonClicked for all interactable Buttons of a Canvas? As in, I got 4 buttons and want the same thing to happen, no matter which Button you press 
u sure?
i have it installed and can't seem to get it to work.
according to their docs yes https://www.doxygen.nl/index.html
Source code documentation and analysis tool
find all buttons on canvas and add listener?
maybe there are better ways to do this
is it? Not seeing it on the doc page, on their github source, or even through Rider. Where are you seeing that type of formatting?
i ctrl-clicked some unity native ( in this case GameObject)
i got 20 canvas with 4 buttons each, so serializing fields for them and dragging every single one in the inspector? theres gotta be a better way
In vsc? If so, then I guess whatever it uses to decompile emits that format. 
find object of type
sure, create a component attach to button, component injects its onclick, component raises event onclick, something else picks up the event
if you only have same button behavior everywhere, i guess you can just GetComponentsInChildren<Button>
yeah, so it would seem
i'll try this out , thanks
guess i have to eat it up for my hate for such docs
do you use any type of event bus?
there may be some extension that simply renders it differently
i.e. while editing you get raw xml view, while not editing you get it formatted for display
Then yeah, it's probably just taking the existing xml and converting it to that. Since that format won't give intellisense hints in VS or Rider. Just tested with VSCode too and it doesn't get any info from that type of structure either.
did the same, seems like that's how they make their natives more readable to people
Makes sense
but it's soo good 😦
Slightly offtopic, but I like the format of rust doc comments: https://doc.rust-lang.org/rust-by-example/meta/doc.html Seems to be in that same type of vain of the vscode decompilation. Very simple I guess.
Oh it's bascially markdown, that's why
ah dw i got it working, i just attached the script to the buttons in the prefab of all my canvases 
dont know what an event bus is XD
I would have probably use pre placed object around edges that define hiding spot instead of relying on the Navmesh. Maybe you could use some sort of tool to automate the placement.
oh nice!
https://docs.unity3d.com/Packages/com.unity.splines@2.3/api/UnityEngine.Splines.NativeSpline.html
NativeSpline is compatible with the job system.
I had no idea this existed!
is there a way to use an int variable as a float in calculations? Just like 1f but instead of 1 having a variable
int foo = 2;
float bar = 1f / foo; // will be converted to a float due to a float being in the operation
float bar = 1 / (float)foo; // can manually convert
either cast it manually, or it will automatically be casted if it's involved in arithmetic with a float
cast?
yes - as in Nom's third example above^
(float)foo casts the foo variable to a float.
Accidently used a while loop in my update function and now my game is fozen! How do I stop play mode if I can't interact with the program? the bg sound plays
Or how do I save/recover the progress of the currently open scene?
nvm closed it. so sad
You can salvage this by attaching a debugger to Unity
and throwing a breakpoint inside the loop
from there use your debugger's immediate execution mode tools to throw an exception or something
e.g. throw new Exception("blah");
that will break you out of the loop
ofc if it's in Update it'll go right back into the loop next frame - so if you can set something in the loop to null to cause exceptions that would be better
You can log errors without any extensions, just do Debug.Error (Or Debug.LogError, one of the two)
I'm not interested in logging errors
I'm interested in throwing an exception to break out of an infinite loop
would break work in immediate mode in a debugger?
I have no idea
i always just throw an exception but it might work too
I would like to enable the canvas with a click event. Without having to use "public GameObject canvas"
i want find the childcomponent with code
so i could reuse the script for other objects
Currently i have this
you need to assign the reference somehow
it depends where this script lives (which GameObject in the hierarchy?)
The script lives in the parent component
Castle?
yes
Then you can do like:
void Awake() {
canvas = transform.Find("Canvas");
}```
just use GetComponentInChildren<T>(true) ?
or transform.GetChild(1) < second child
or this
But can you use this OnMouseDown?
you could but you shouldn't
you should do it in Awake
I want to open a ui when i click on the "castle" object. That's why i ask
get the reference in awake
use the reference in OnMouseDown
OnMouseDown is fine for now but there's a newer more flexible version of it if you're interested for later
it's called IPointerDownHandler
or IPointerClickHandler
Oh thanks i will look into that!
Hey there, I'm having a known issue with the Input System where if you rebind a key, it won't update the generated C# classes. One of the Unity developers said you can still use the generated C# classes, but you'll have to dynamically set the action references. I'm not sure what this means exactly and how I could go about doing this.
You just use
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_SaveBindingOverridesAsJson_UnityEngine_InputSystem_IInputActionCollection2_
and
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_LoadBindingOverridesFromJson_UnityEngine_InputSystem_IInputActionCollection2_System_String_System_Boolean_
not sure what they mean about dynamically setting action references in this context
rebinding a key is presumably something you're talking about happening at runtime
we can't write new code at runtime
I've got those two in a separate script and they work. The issue I'm having is that the rebinding only works in the main menu and not in a game. In the game it does save and show the correct key, but the player's controls stays exactly the same, until I go back to the main menu and into the game again.
Reading the person's post again, he says it works best with the Player Input (Which I'm using) or .inputactions directly. So I'm not sure what's going on.
sounds like you have two separate InputActionAsset instances
and you're only loading the binding overrides into one of them
If you have a PlayerInput component - that component has its own InputActionsAsset copy
and so would a standalone instance of the generated C# class
also if you have a new scene being loaded and you are therefore discarding the PlayerInput from the previous scene, you will have to load the binding overrides again since you now have a new instance of the input actions asset
Is there a way to regenerate/replace that copy with the new one? From what it sounds like; the rebinding script is updating the .inputactions file and not the copy on the PlayerInput component, which is why it works when I reload the scene since it's making a new copy of the .inputactions file.
although I can't say I ever tried to do that at runtime. It should probably work
the other option is to just do cs void Start() { myPlayerInput.actions.LoadBindingOverridesFromJson(bindingsJson); }when the new PlayerInput is created
I think I could convert that script to work so whenever a rebind is finished it executes this code on the player.
I'll try it.
so guys i have my player movement script which was working comepletly fine and all of a sudden it doesnt move the player
using System;
using System.Collections;
using System.ComponentModel.Design;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float playerSpeed = 10.0f;
public float playerSpeedBuff = 5.0f;
bool isDashing = false;
public float dashSpeed = 50.0f;
public float dashDuration = 0.4f;
public float dashTime = 0.0f;
public float dashCooldown = 0.10f;
Vector2 mousePosition;
public Animator animator;
public Rigidbody2D rb2d;
public Camera cam;
private Vector2 moveInput;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
cam = Camera.main;
}
void Update()
{
Debug.Log(Input.GetKey(KeyCode.W));
Debug.Log(Input.GetKey(KeyCode.A));
Debug.Log(Input.GetKey(KeyCode.S));
Debug.Log(Input.GetKey(KeyCode.D));
moveInput.x = Input.GetAxisRaw("Horizontal");
moveInput.y = Input.GetAxisRaw("Vertical");
animator.SetFloat("Horizontal", moveInput.x);
animator.SetFloat("Vertical", moveInput.y);
animator.SetFloat("Speed", moveInput.sqrMagnitude);
if (Input.GetKeyDown(KeyCode.Space))
{
isDashing = true;
dashTime = dashDuration;
rb2d.velocity = playerSpeed * moveInput.normalized;
dashCooldown = 0.10f;
}
}
void FixedUpdate()
{
if (isDashing)
{
rb2d.AddForce(dashSpeed * moveInput.normalized, ForceMode2D.Force);
dashTime -= Time.fixedDeltaTime;
dashCooldown -= Time.fixedDeltaTime;
}
else
{
rb2d.velocity = playerSpeed * moveInput.normalized;
}
if (dashTime <= 0)
{
isDashing = false;
dashTime = dashDuration;
}
}
}```
This is my current code for a 2d game I wanna make, some1 pls help me add player rotation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Rigidbody2D body;
float horizontal;
float vertical;
public float runSpeed = 5f;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
}
}
Do MonoBehaviour's InstanceID match it's GameObject one?
how
It does not as far as I know. Each UnityEngine.Object has one.
hi! i plan to have tons of canvas' in my game and im wondering at the performance impact of it. for reasons, the canvas' always need to remain on but i can disable the elements in the canvas. will these canvas' that dont have any active objects to render still have an impact on performance?
if they are completely empty then no
no they are separate objects hence have separate IDs
canvas is a way to optimize transform hierarchy, canvas stops update transform event propagation
so the more the merrier
cool, thanks for the answer!
Not sure how many people use visual scripting here, but I'd like to access its scene variables with C#. Here is a snippet of my code which almost works, besides it isn't wanting to use the Unity.VisualScripting API.
using Unity.VisualScripting;
private GameObject player = (GameObject)Variables.ActiveScene.Get("PlayerGameobject");
what does "it isn't wanting to use the Unity.VisualScripting API." mean?
Sorry about my lack of context, here's what the error says "The name "Variables" does not exist within the current context".
what version of the Visual Scripting package are you using
I am using the latest one; Version 1.7.8 - May 10, 2022.
Are you seeing that error in Unity too, or only in VS?
It is also in the editor.
Ah this is in the input system samples?
Seems like you're trying to edit them?
Yup.
My guess is the input system samples have an assembly definition
OH RIGHT!
(if you show the top of your VS you'll see the assembly you're in)
I had to add TextMeshPro to have it work!
Hmm, there doesn't appear to be an AssemblyDefinitionAsset just for Unity.VisualScripting. There are different variants like Unity.VisualScripting.Core.
Most likely core is what you want
Alrighty, it was the core one. Now I have a lot of errors, but they all explain what I need to do to fix them.
Does setting rotation to AudioSource's game object make any difference at all?
Hey, any suggestions of libraries to send/receive events from a server(asp.net) ? It's not performance-critical so I just want something that works and looks clean.
UnityWebRequest
Hello. I am struggling with something in Unity 2D. I am spawning some tiles (square sprite) via code in order , to form a grid 5x5 in positions x=0, y=0 to x=4 y=4. The code is
//Initialize grid to 0 values and spawn tiles
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
int rgb;
GameObject g_tile = new GameObject($"Tile x: {x} y: {y}");
g_tile.transform.position = new Vector3(x, y);
g_tile.transform.parent = gridManager.transform;
var sRenderer = g_tile.AddComponent<SpriteRenderer>();
sRenderer.sprite = sprTile;
rgb = (x + y) % 2 == 0 ? 1 : 0;
sRenderer.color = new Color(rgb, rgb, rgb);
}
}
}
The Result is a grid with black and white squares. like a chess but in grid 5x5.
What i want to do?
I want to each of these tiles to have a child TextMeshPro in the center with a number (any number this is not the problem). How can i spawn TextMeshpro inside these tiles?
Ignore the apples and the owls and the beaver
If the pivot is not centered (and its Spatial Blend is set to 3D), it could, but the audio is affected by the min and max ranges of the source, if those ranges move further from the listener due to rotation, then it could affect it - in most cases, I would imagine this wouldnt have any affect on how the sound is heard (maybe except for the doppler levels in one ear or the other, if the rotation is fast or instant)
nah, position is const, only rotation is at question
Ah, in that case, for 3D sounds, it shouldnt have any affect on how the audio is heard
for 2d it seems to be irrelevant either
Right, for 2D, its always played at the (headphones) level, and not from the world so the distances woulnt affect the listener
oh well, g ood stuff
Is there a way to completely create and initialize animator controller inside of code?
I want to store my animation clips serialized on a weapon and on start initialize a controller and dynamically create it, with states and transitions, which are the same for all weapons.
The key goal is to avoid manually creating controllers for each weapon. Is there a good way to do this?
You can use AnimatorOverrideController.
you just spawn it? I dont understand what the problem is
create a prefab for text, spawn that prefab
That actually looks like something that could solve this issue, thanks
You can also make your transition with Animator.Play instead of the Animator transition from the StateMachine.
i tried this code but the text isnt shown.
GameObject tileText = Instantiate(textPrefab, g_tile.transform.position, Quaternion.identity);
tileText.transform.parent = g_tile.transform;
inspect the object in the scene after it's spawned
check out why it's not visible
i was thinking if i could add a textmeshpro component but i get an error. For example
var tileText = g_tile.AddComponent<TextMeshProGUI>();
tileText.text = "my number";
But this does not work.
you have mistake
because it already has a SpriteRenderer
you can only have one graphic/renderer on an object