#archived-code-general
1 messages · Page 101 of 1
filesystem access issues suggest the problem lies with the OS, or at least outside of Unity - it could be any number of things, but generally the issue boils down to the same thing: something is accessing that file, and you're not allowed to change it while it is
could be as simple a fix as restarting if some process didn't end properly - it might be drive specific, sometimes external drives don't have the same permissions by default, might be some local backup software you have running like OneDrive/Google Drive
Is there a way to have game object in a scene which only exists with some #define?
or if MonoBehaviour attached is fully wrapped in define, will it be fine to leave game object as it is? (it's probably will be just empty transform)
I believe Unity will be upset during deserialization, so I don't think this is very well supported.
Assuming it allows you to build
Any alternatives to that then? I am trying to publish app to multiple stores which require different sdks
You can separately define out methods and includes
Sounds awful ngl
Seems common to clean this up by creating separate provider objects with a shared API.
well yeah, high level API is fine to use defines, but it comes to relying on different game object implementations
since some SDKs require interface on MonoB
I'll have to play around I guess and see how it works
Whole MB/GO exclusion probably works better when paired with Resources/Addressables.
What's the difference between slider and scrollbar?
in relation to what: the editor, ui, etc.?
there are UI Components slider and scrollbar. What's the difference between them, if they (i think so) do the same functions actually?
we're just getting the value from them and doing whatever we want
did you read the descriptions for each component from the scripting api?
no, I didn't
that would be my first stop . . .
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-Scrollbar.html
oh, I see
so Scrollbar is used to control a big amount of text, and Slider is used for whatever else
so slider is better for me to use in my current context
no, they are unrelated concepts
slider is used to provide input
you drag the handle between the minimum and maximum value
the link i sent explains what both do . . .
is there possibility to make it from 0 to 100 using just int parameters?
so that user cannot make it 0,4323 or 57,432432
you can set the snap value
just ints
snap value?
oh wait, you don't set a snap value
you just tell it to use whole numbers
i was thinking of sliders in the browser :p
You can make sliders snap to increments in Unity, too, but you have to hand-roll the code a bit..
I'm trying to add assembly definitions to an asset which doesn't have them so that their scripts can be referenced in our code. I've mostly found the right assemblies, but am having trouble finding the assembly to reference for LitGUI:
What assembly is it in?
It is not in any of these:
Are you using Rider? If so it says if you open it
hatebin isnt working for me rn idk why... Will this health script work, like the regeneration part
Might be slightly different though since I am on HDRP instead of universal
Will this work for a regeneration script... https://pastebin.com/ehRPFkEz
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.
Have you tried it? Nobody is going to set this entire thing up to verify it for you.
but im trying to fill it with game objects
points is serialized
it probably got serialized with a length of 0
the default value is overwritten when Unity restores the serialized values
initialize the array in Awake
o ok
default values get assigned as the object gets constructed
deserialization happens after that
its still erroring why doesn't this work
because if the length is 0 then index 0 is out of range
(if the length is 0 ANY index will be out of range)
why are you doing i < 4 in your loop instead of i < points.Length?
cos its supposed to be 4 points always
I would do that anywhere else
clearly it's not 4 points though
I was trying to set the length
so something is wrong with your logic
100% of the time you should use the array length
not a hardcoded value
well I would be even more confused if it didnt go through the loop at all
clearly your array is not the right length here - start investigating why
if it wasn't 4 I wouldn't know that the index thing was an issue
sure you would - you would find out in about 30 seconds with log statements
or by attaching a debugger
hm
show your code.
all of it
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
hey guys In my canvas, an 2 image is showin up as a red cross in my scene view, and it does show up any idea what this might be?
that means the element has a negative width or height
who are you replaying sorry?
you.
your RectTransform has a negative width or height
yeah
humm ok, it does not
I made a for loop to try and do it in the same function
if it's set to stretch, you might have the top/left/etc. values set too high
you need to initialize the array once
an array has a fixed size, which is set when it's created
didnt seem to work either
yes, that doesn't initialize the array
that sets elements of the array
points = new GameObject[4]; will create an array of 4 gameobjects and store it into points
this does, yes, but you deleted it from your code..
(i am referring to the second image)
i do not understand your question
fixed thanks
why would you need to "re-add" the component?
it runs when the component is created and the game is running
so, for objects in the scene, it will run on startup
well this script can run while the game is running
for newly created components, it runs immediately after creating the component
so, setting points in Awake is a reasonable idea
i don't believe it will run if the game object is inactive, though
yeah
so, if you called InstantiateConnectors on a component on a disabled gameobject, Awake wouldn't have run yet, iirc
idk why but it was working b4, just when I added it to a new object it stopped working
you should make sure the error is coming from the object you think it is
click on the exception in the console; it should highlight the offending object
it is because InstantiateConnectors runs when you click generate connectors button in its editor
oh.
yes, that would, indeed, do it.
i would initialize the array in that method, then.
which is what I did before but I dont understand why I cant initialize it like this
because arrays have a fixed size
that code is storing four new objects in the array
it does not make room for four objects in the array
this code will throw an exception if the array's size is less than 4
and this code does nothing to change the size of the array
hmmm
since points is serialized, Unity will create an array that holds 0 elements by default
you'd then add and remove elements in the inspector
so this would
yes
alr
it sounds like the job of InstantiateConnectors is to set up the contents of this points array
therefore, it should also initialize the array
Which do you guys think would be more performant? Using an array for a group of items that are updated every update, but the items continue to get updated after they are no longer needed because removing them from the array is a pain. Or switching to a list and having the items removed once they no longer need to be updated
Use a list
In C#, accessing an index that does not exist results in an error, even if you try to null-check it. Unlike languages such as Javascript, which would return undefined. In the case of the array, you should check the length beforehand and then do a null check to have it short circuit in case it does not have the index. Alternatively, use GetElementOrDefault which will do the heavy lifting for you, and return default (which would be null) if it does not exist.
When it comes to c# performance, it really does not matter. Lists create more garbage, but are much easier to use. That garbage is negligible when it comes to performance speed, though.
yeah, it's negligible
do whatever's easier to understand
not easier to write: easier to understand
programming is mostly reading other people's code
including the code you wrote two weeks ago (it is basically someone else's code now)
GameObject*
💥
actually i'm not sure you can have a pointer to a managed type
I have never heard of a span
but I did switch to lists and it is easier to understand, thanks
because now I don't need a seperate value on every item to tell if it has been deactivated or not
I can just remove it
I've been working on my game on and off for like 8 months and I understand that now
the next one I do is going to be so much better organized from the start lol
hi, is there a way to access the burst cycles of a particle system in unity?
I have some particles that burst with a probability of 0.25 and i want to play an audio each time it does a burst
I can probably count the particles and check when the number increases but for my use it doesn't work as good
any alternatives/solutions?
I've never used particles but you should check the Unity documentation and see if there are any methods / properties that will allow you to do this
I have searched the documentation and this didn't come up once
check out those documents
I googled "unity particle system burst"
Unfortunately, this is another dead end for me, there isn't anything here that will help me in my situation
I was looking for sort of a Unity Event that is invoked each time the bursts happen
Maybe control the bursts yourself. Turn off looping and Play the particle system from code manually
Play your sounds from there too
Hey guys, is there a way to keep one of the arm fixed to a position while the rest of the body plays an animation? For example, I want to attach one of the arm to a weapon such that they are holding the weapon (left hand on the barrel). I have used Two Bone IK for that but it seems like the arm moves away from the weapon when I walk / run.
you need to add Rig Transform to the weapon
Hey, the object I'm instantiating isn't a child of the transform I give, I don't really know why. Any ideas?
is holderInstantiate what you think it is ?
Yeah
What would that do? I am still fairly new to the animation package 😅
how did you check it didn't work
2 sec
Nvm I changed the transform in code ><
Thanks
What could be wrong with loading this FBX model?
GameObject tubeModel = Resources.Load<GameObject>("Models/Connector");
componentTypes.Add(new ComponentType("Tube", new List<Vector3>() {
new Vector3(0, 1, 0), // Top
new Vector3(0, -1, 0) // Bottom
}, tubeModel));
Okay, I was also confused about using two - two bone Ik constraints (one for the left and one for the right hand). Currently, I am just using for the left hand so that they place their hand on the barrel but is it recommended that I do not use animations for the rifle stance and just use IK to create a rifle holding pose?
What I currently have in my head is the following:
- Every weapon will have different locations where the character will hold that weapon hence, I'll create a game object for describing the position of the left hand (and another one if I am using 2 two bone ik constraints for the right hand position).
- I'll update the Rig's target transform (from script) to those game objects and build the rig again once the weapon drawing animation is finished.
Is this the proper way to utilize the animation rigging package?
sounds about right
keeping the IK targets on each weapon prefab is also an option
then assign the target when weapon is equip
Yeah that's what I am doing, I am keeping the targets on the weapon since that'll make it more dynamic and easier to configure
if you want weapon to move with rig/animation then you need a rigtransform
so it will act like another bone
But that's what I want to know, should I use 2BoneIK on both hands or only on one?
that's up to you or you original weapon posing animation
my right hand typically just has multi-aim constraint
Scriptable object...I have a field for string. Is there any way to make the field expand to be the size of the string? I have naughtyattributes but didnt see anything for jt
(In inspector)
Yeah that...how might that actually look in code?
[Multiline(10)]
public string hello10Lines;
[Multiline]
public string hello;
Oh sweet thx
or specify lines
Is there any build-in method to parse number into format minutes:seconds
188 => 3:08
45 => 0:45
636 => 10:36
Timespan?
maybe you can give me an example of code or a link?
it should be parsed from audioSource.clip.length that is float
I’m at school and I just made it, will it work?
Will this work for a regeneration script... https://pastebin.com/ehRPFkEz
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.
I just googled seconds to minutes unity on my phone and stuff for timespan came up
I’m at school rn
ok, thanks
@sour zealot You should wait until you're actually able to test it then. This discord isn't your personal compiler.
And if it doesn't work, you can ask follow up questions.
Can someone explain where the transform is coming from in this instance?
My assumption is it's getting the transform of "this" i.e the object where the code is written. But I need confirmation.
The object the code is on
ah thanks
Aka A isnt able to call scripts in B that it inherits from?
it is able to call it I just dont want to have "inherited functions" section in every Update() of any derived class
the ideal would be to have Update() in B with all of them, and B considering that A is overriding them, but it doesnt work
follow up: is it getting the world transform or the local transform?
🐵
world transform unless is localPosition
was the "unless its a child class" a mistake?
toss both update codes here? (or first few lines of both)
it's always world position
oh its always world position. Thanks
@rotund burrow
A : B
B : monobehavior
A example
protected override void Start()
{
hpText = GetComponentInChildren<TextMeshProUGUI>();
base.Start();
Shoot();
}
B example
protected virtual void Awake()
{
stats = new();
myJumps = new();
pauseShooting = true;
}
not quite working as I was hoping
[CreateAssetMenu(menuName = "Heroes")]
public class Heroes : ScriptableObject
{
public List<HeroInfo> heroesInfo;
public VisualTreeAsset heroesPrefab;
}
[Serializable]
public class HeroInfo
{
public string name;
public AllHeroes hero;
public Sprite head;
[Multiline]
public string bio;
}
ex) if you look at the bottom Void Dragon...the text goes off the screen and doesn't wrap around
looks like it working to me, what exactly is issue?
I don't think wrapping text does work in inspector
not vanilla at least
I found something like this...not sure where to put it 😄
EditorStyles.label.wordWrap = true;
oh nvm that was from 8 years ago
any idea how to fix that...or what people normally do when needing to put a bunch of text ingame for bio's or something
nvm
found a fix!
[TextArea(15,20)]
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
How do you make these components? What are they for?
scriptable objects
Are they like different characters you can select in game?
unlock but yeah
I use scriptable objects pretty often to store data that wont change that I need in places
Do I have to install scriptable objects or does it exist within unity components
already exist...might be worth watching a youtube video about them 🙂
Ah, found a video! Thanks for letting me know 😄
Also, to get that "Name, Hero, Head, Bio" etc. Is it all done in code and it appears in the editor?
@swift falcon pretty much, my code looks like this
except TextArea instead of multiline
I ask the question and the next thing in video was an answer to my question 😂
Hi, I'm trying to generate multiple arrays of int containing random numbers that doesn't repeat between each other. For exmpl:
Given umbers: 0-9
I want to get 5 arrays like this: [ 5 , 2 ] [ 4 , 7 ] [ 6 , 3 ] [ 8 , 0 ] [ 9 , 1 ]
Any idea on how I could approach this?
Thanks tho, I got to learn a entire new thing because of you 😄
- put your numbers in a list
- shuffle the list
- iterate through the list grabbing each pair of consecutive numbers as you go
pseudocode:
List<int> numbers = { 0, 1, ..., 8, 9 };
Shuffle(numbers);
for (int i = 0; i < numbers; i += 2) {
int[] pair = new { numbers[i], numbers[i + 1] };
// do whatever you want with the pair
}```
Thanks I'll try that
Hi, I'm trying to set some random offset on my animations. I have the following code:
_animator = GetComponent<Animator>();
_animator.SetFloat("Offset", UnityEngine.Random.Range(0f, 1f));
}
however the default state is always played without offset. Once the default state is played once it works fine and in the animator window I can see that the Offset parameter is set correctly. It is only for the first cycle of the default state that it does not work
of course it does not work
your idle state plays at the beginning
when the game starts
you should consider doing another animation with Coroutine like offset if I do understand what you need to do
How can I prevent the agents from pushing each other?
They are trapped in a disconnected room, and I command them to reach a point outside it.
So they moved to the point inside the room that is closest to their destination point outside it.
However, they are pushing each other in order to reach that point...
¿How can I make that agent stop push each other?
you need just to stop them moving I guess?
Yes
so OnCollisionEnter ??
they will only push each other if they are NavMeshObstacles, no?
But what if they collide in a different situation, like running to two different points?
yeah, move them in other directions in order to avoid each other
You can't put a NavMeshObstacle as component in a NavMeshAgent
can't you?
The Agent will try to avoid itself
@neon plank or do it so that the Vector3.Distance between them cannot be less than minDistance, otherwise change their moving direction
How would then handle the case where two agent travel to two different directions and meet in the middle? Both wouldn't stop? I don't want that
guys how do i make it so when I instantiate a prefab with a script, the script finds a specific object in the scene
GameObject.Find(strings)? Thought I wouldn't recommend such brittle approach
here rotate both agents without changing move direction
last place on international drawing Olympiad💪
¿And if they are trapped in a room which doesn't have a connection to reach its destination?
Agents will try to move to the point inside the room closest to the destination point. But if they start to rotate when near with other agents, they will get stuck in a loop, getting away and near the point constantly.
where do they need to move actually?
That is the point closest to the destination. So the 3 agents try to stay in that point.
If they start rotating they will get stuck in a loop.
yeah, so you need to stop them?
Yes, but how do I determine they should stop in this particular case and not in others by accident?
so when they stuck there, they stay in collision for quite a long time
why don't you count the time with OnCollisionStay?
If the 3 agents decide to stop in order to avoid pushing all the time, and then at runtime the navmesh changes (e.g: a door is opened) so now there is a path to move. ¿How will they realize they should start moving again?
weird question
just make them move again when the navmesh is changed ??
What if the nav mesh changes in a form that not necessary allows the agents to move?
that's possible when the direction point is +- the same as the previous one
in this case they just gonna stop moving again
otherwise I do not see any reason why they cannot move
Ok, I will try
good luck
i would randomize their destinations a bit, so that they don't all try to occupy the same space
and then snap the destination to the navmesh with SamplePosition
although, that could wind up snapping to the wrong side
What you mean with that?
exactly that: use NavMesh.SamplePosition to get a position that is on the navmesh
although, iirc, agents will already just try to get as close as possible and then stop
Exactly, they do that. But if two agents want to get in the same exact spot, they push each other
thus the randomization
Ok
maybe im thinking too easy right, because idk how important it is for them to keep remembering to go to that point. like if you can change something and want them to instaly act on it this might not work. but cant you tell them to forget about trying to move there once theyve reached it once? that way they might push eachother for like a very brief moment by which time they all been at the spot and stand still pretty close by?
I guess, I can try to adapt my code to do something like that
Hey everyone. A small question. What is the best system to save a lot of data in a game(like whole classes of characters, instantiated objects etc)? As I see using Binaryformatting isn't the best way to do it.
Json is an acceptable save format.
Can I store a class there, tho?
that's neat. And what about saving instantiated objects?
where did you get that idea from? Binary serialization is a must for large volumes of data
I am working on a survival horror game. The player has a flashlight. I want to make enemies notice when the flashlight is being shined...
- in their eyes (easy)
- on a surface they can see (uh oh)
i'm not sure how to handle that second one
I was just looking and different approaches and saw a lot of negative posts about binary formatting
I guess I could do some rudimentary path tracing
shotgun rays out of the enemy's eyes, then see if any can make it back to the player
oh, yes, that's exactly what I should do
I think you are confusing that with the Binary Formatter class
you probably saw something about the BinaryFormatter
probably
i think it gets a slightly unfair bad rap
it does
it's not as catastrophically bad as, say, Python's pickle
which you can trivially tell to run arbitrary commands
how do I use binary without binary formatter then?
"binary" just means that the data is not in a text format -- i.e., something that a human being could read
there are other binary serializers, BinaryWriter springs to mind
it's a lot harder to understand binary data by just looking at it
it's significantly more efficient, though
consider how there are what...62 alphanumeric characters?
you can encode 256 different values with a byte, so a format that only uses those 62 characters is going to be four times less efficient than a format that can just write anything it wants
a binary format can also directly represent data, rather than requiring a conversion step
consider storing the string "1000" vs. just storing the actual value
...although, in that case, a 4-byte int would be just as efficient as a 4-char string :p
a large number would skew that.
ok, thanks, I'll try using BinaryWriter
I have another question. I can't find how to write a class with BinaryWriter, how do I do it?
In the SceneView.duringSceneGui callback of a custom editor is it possible to know which element of an array the use has currently selected?
For example in this case it should return 2 since I am selecting the Element 2 of the array
Manually, that's the catch they didn't mention. You need to have a fix on what you write and in which order, as you'll have to do the exact same for BinaryReader when reading. It's a tedious task, and if disk space isn't a concern I'd just use JSON.
JSON.NET (a lot of people call it Newtonsoft.Json, since that's the namespace you'll use) works pretty well.
How to render an object on canvas A above anything on canvas B, when canvas B has a higher sorting order?
(specifically for draggable objects which you want above everything else while dragging)
add a new canvas component or make a dummy draggable object that is higher in the ordering
or a dummy draggable object with a canvas component
Is it smart just to make every draggable object have it's own canvas?
it's smart to break up your UI into multiple canvas
honestly when I've done draggable objects I've often just used Graphics.DrawTexture
but for slots it creates problems
batching issues or something, honestly didnt read too much up on it
is there any way to toggle a bool
on and off
at the same time
not like bool = !bool
but like when I press it, it sets true, and one millisecond later it goes false again
How can I change the API using a dropdown? I can’t find any tutorials or anything
what are you trying to do?
im triyng to do a health regen script
this is the script
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.
if im doing something the hard way, please lmk
well, you have like five copies of the same thing in that RegainHealth coroutine
i'd just store the last time you got hurt
if lastHurtTime + regenDelay <= Time.time, regenerate health
that's how I do stamina regen in one game
what part of it confuses you?
oh
i wrote deltaTime
whoops
force of habit
if you got hurt at t=8 and you have a 3-second regen delay, then you're allowed to regen health once you get to t=11
if you get hurt again at t=10, you don't regen until t=13
Hey again. Json works fine for me but I'd like to know how do I store scriptable objects as a variable? Json gives me InstanceID, is it reliable to store it this way?
no, it's super unreliable
Can someone help
i'm not sure if there's a particularly "correct" way to do that.
My current strategy is to give each scriptable object a GUID (i actually just yoink the GUID from the asset)
I use a custom json converter for the SO
the writer just grabs the GUID and writes it as a string
the reader decodes the GUID, then looks the SO up in a dictionary
the dictionary is populated by using Resources.LoadAll
can u just give me code?
no, I'm not going to spoonfeed the answer to you.
lol
is this not clear?
can u explain more
i don't know what to tell you if you just say "please explain more"
suppose the regen delay is 5 seconds
if you get hurt, you can't regen for 5 seconds after that moment
i want you to implement this idea. it's very little code.
and no, it does not involve a coroutine.
do you know how to get the current time?
nope
Hmm. Can I just make an array class that has 2 variables: scriptableobject and integer. Then I'd just populate the array with all scriptableobjects and will be saving only the id(the integer that this scriptableobject has)? Is it inefficient ?
Time.time
then what
write that to a field every time you get hurt
a field?
float lastHurt = Time.time;
shhhh
if you do not know what a field is, then you really need to do some more reading...
i do
i was suprised why we would need a field
float lastHurt = Time.time;
is this right?
because you want to remember the value
That's not a field
putting it in a local variable and then immediately throwing the variable away does nothing.
what is he doing, btw?
health regen
and what's the problem?
get hurt, wait 3 seconds, start healing
🫠
i am the problem
this is what you need to do:
- when you get hurt, update the "last hurt" time
- every update, check if it's been at least 3 seconds since the "last hurt" time
- if so, add health
the most basic variant for me is using a timer that you set to 3 in OnGetHurt() and in Update it'd just be decreased every frame
it doesn't work or what?
that would also work
ye but i need to interupt the regen if I get hurt
yeah
it'd handle this
@sour zealot You've been told before you should be posting in #💻┃code-beginner. Your next question goes there.
I like mectorn's idea more. It is more intuitive.
okay
count down to zero
OnGetHurt puts back the timer to 3 and resets regen time
Secondly, you don't need coroutines for regen. You can just track time in Update and when it surpasses an amount of time, you get health back. Reset the timer to zero and let it continue.
private IEnumerator RegainHealth()
{
while (health < 100)
{
yield return new WaitForSeconds(1);
if (damageTaken == true)
{
StopAllCoroutines();
StartCoroutine(RegainHealth());
}
yield return new WaitForSeconds(1);
if (damageTaken == true)
{
StopAllCoroutines();
StartCoroutine(RegainHealth());
}
yield return new WaitForSeconds(1);
if (damageTaken == true)
{
StopAllCoroutines();
StartCoroutine(RegainHealth());
}
yield return new WaitForSeconds(1);
if (damageTaken == true)
{
StopAllCoroutines();
StartCoroutine(RegainHealth());
}
yield return new WaitForSeconds(1);
if (damageTaken == true)
{
StopAllCoroutines();
StartCoroutine(RegainHealth());
}
health += Time.deltaTime * regenSpeed;
yield return null;
if(health >= 100)
{
StopAllCoroutines();
}
}
yield return null;
}
``` hgeheheheheheheheeehe
that is my current one lol
dude...
You can move it to #💻┃code-beginner
yes I know
I like that you stop everything, even not related to regen 
Has anybody ever implemented a Game Manager with interfaces? Like this : https://hatebin.com/twjiqztmqk
I can see this being beneficial in that its more secure as you could only access certain properties/logic by what the interfaces methods expose. Also I guess its more organized and easy to tell off the cuff that a script utilized a singleton? (Even though your editor can help with that idk). Maybe good for team projects too? Or would it just be annoying/unnecessary? Thoughts?
depends on your style, if you aim for IoC and/or use DI containers and like to treat unity as a view into your POCO game logic, this makes a lot of sense
I created a test script, but the test script doesnt seem to have access to any of my other scripts. so how am i suposed to test them xd
How can I make it find them?
even just as a way of making explicit what part of a class is used by another that holds a reference to an interface it implements can be beneficial
Hi all, look for some help. Trying to do the following:
- I need to be able to send the model created by the user to the backend
- The be able to view and modify the model upon retrieval
However, I am not able to retrieve it. Any help would be appreciated
You haven't posted any code.
nor do I think you're going to have an easy time hot loading 3d models in at runtime using binary data
https://github.com/AtlasFoundation/AtlasAvatars-CharacterCreator
Using this for my final, and stuck trying to retrieve the model
I don't know anything about that, sorry.
You'll probably be better off serializing each avatar's individual attributes
and then rebuilding it based on that
How are you serializing it right now?
I hope you aren't trying to send raw object binary data over the internet and constructing objects with that
I was.
Let me guess. Binary formatter?
That's how you get hacked. Microsoft warns against it for good reason.
Back to the point: Just pack up each avatar's individual features. Hair color, hair type, skin color, etc
then you can probably rebuild it from that.
Yea I’m not optimizing for security. But the idea of serializing attributes makes a lot of sense. I just have to figure out how to do it.
Any advice of documentation you'd suggest?
yep let me find it
You can safely write and read binary data with this. It lets you serialize all primitive types
If this is too advanced, just use json
binary writer only does primitive types (thats why its safe), for advanced types you need to supply your own serialization/marshalling and security checks
no what's that
welp I fixed my issue, but it's a package for streaming unity content on the web via webRTC
for like presentations or something?
ah I see
https://youtu.be/c2pp_T5xzeU
yes it's pretty cool but a bit janky, I had issues with trying to read my mouse via browser but alles gut
so I'm having an ienumerator problem. when I do this:
yield return StartCoroutine(cardAnimation());
print("it reaches here just fine");
removeCard();
updateHand();
placeCardOnTable();
but I want to remove the card and update hand before the coroutine. but when I do this:
removeCard();
updateHand();
yield return StartCoroutine(cardAnimation());
print("for some reason nothing after the coroutine runs now");
placeCardOnTable();
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
What's the best way to sync up Animators? I have one for hair, body, etc
are you destroying or disabling the object this script is on?
no.
removeCard();
what does this do?
removeCard(); removes the card reference from the Hand
updateHand(); does destroy and remake the card objects, but this is happening in the game controller.
maybe ask in #🏃┃animation
do you have any errors
no exceptions thrown.
oh this script on the card object?
no this script is in the game controller.
do you change timescale at all ?
no
no print either after yield return ?
only in the second case, yeah.
That would mean that either the current coroutine is being stopped (for example if the object that runs it is disabled or destroyed), or that the second coroutine does not return control to this one(either stuck in a loop, stopped or waiting for another coroutine).
cardAnimation(); creates an animation object (from an animation controller) then yield return new waitForSeconds(that object's lifetime)
Add a log after that yield. Also print the life time before the yield.
in this order, it reaches all three break points.
in this order, it reaches only the first two break points.
What's coroutine here?
It looks like you didn't read my message properly. I was referring to the inner coroutine.
the only yield in the second enumerator is a waitforseconds, which according to break points it gets past, but doesn't return to the first. and only in the second order.
Add an OnDisable to both the classes that run the coroutines and print something meaningful there.
I will eat something comically inedible if either of these objects are being disabled.
it made me nervous for a second but no, it only gets there when I stop the game.
Ok so I was doing a workaround where I would just disable the sprite on the card display. and decided just to try disabling the gameobject, and apparently that also caused the issue. RemoveCard destroys that gameobject, but that's a void and otherwise it isn't where either enumerator is running...
...but yeah disabling the sprite before the card animation is at least close enough to what I need to do that I'll just give up and go with that.
trying to do a thing where i have two rigidbodies, i want it so that if i move rb1, it moves rb2, and vice versa. and then when i block one from moving the other one stops moving
could probably just set rb1's velocity to rb2's velocity and vice versa
that'd make some really weird behaviors
i have a coroutine where it needs to return a list of data classes, the coroutine is done and without errors, however, i cant do it like this right?
private async void updateHistorical(List<UserActivity> activities)
{
completedQuests = StartCoroutine(RetrieveCompletedQuestFromActivity(activities));
HandleCompletedQuest(completedQuests);
....irrelavant codes...```
basically it's a set of two sliding doors, if you open one the other one opens too in the other direction.
how are you opening them. to be fair, you were pretty vague
does coroutine has .Result or something like that?
time to use UniTask
whats that new stuff
can you only open one, so it's either one?
and is the direction fixed
// You can await IEnumerator coroutines
await FooCoroutineEnumerator();
so you can select either door, and both doors just open?
the direction is fixed, i'm just applying a pull force to a set point in front of the player, i've got a universal script for moveable objects.
it's done via rigidbodies
so you open the door with physics
yeah
you could use inverselerp?
@worldly hull with unitask using coroutines becomes pointless
some sort of lerp, you check the progress of one door, then you move the other door
in any case since that is not what you asked
welp i need to inform and discuss with my team first
lol i cant just add random packages into my team project 💩
the problem is that I need both doors to respond with physics, if i make one door just follow the other door then one door wouldn't react with physics
but i will check it out
im not aware of any mechanism apart from class member field that could inform the coroutine state
public sealed class Coroutine : YieldInstruction
{
~Coroutine();
}
yay
minimalism
i understand, there is also alternative - MEC from asset store
both resolve most coroutine issues
havent used unity coroutines in years outside of editor coroutines package
this seems to work
@worldly hull well actually if you pass a callback to the coroutine
you would while it
dw , even if i cant install this, i can still use it in my own project 👍
or some general token object
i thought of a stupid way but still be able to do it
class CoroutineCompletionHandle
{
public bool Done {get;set}
}
IEnumerator DoStuff(CoroutineCompletionHandle handle)
{
// does stuff
handle.Done = true;
}
Task.Delay(500);```
give me my kekw emoji
idk how u feel about this, but our ways to spawn all in game objects are using addressables asyncs
team project ofc, not in my own project
dont feel because practically zero experience with adressables
all the interactables and NPCs and parts of the UI will be spawned using this function
and in the function of calling this coroutine, the function is actually an async function, cuz it needs to spawn something out
so i can still use Task.Delay there
yes , we use this kind of method to spawn stuff
nevermind this doesn't work either
can use similar method to call coroutines globally
welp i can just change the coroutines to void
https://forum.unity.com/threads/cannot-start-coroutine-within-method-called-by-unityevent-if-singleton-is-used-ui-button.1435414/
If someone knows a fix for this let me know.
It seems to be impossible to start a coroutine from a singleton script using Unity Events
SongManager.StartSong SongManager is a type name?
this is the call
private async void updateHistorical(List<UserActivity> activities)
{
ProcessCompletedQuestFromActivity(activities);```
this is the function
```cs
private void ProcessCompletedQuestFromActivity(List<UserActivity> activities)
{
List<string> completedQuestid = new List<string>();
List<UserActivity> completedQuestActivity = activities.Where(x => x.type == "QuestComplete").ToList();
foreach (UserActivity activity in completedQuestActivity)
{
completedQuestid.Add(activity.refId);
}
completedQuests = QuestManager.instance.questLog.questsData.Where(x => completedQuestid.Contains(x._id)).ToList();
HandleCompletedQuest(completedQuests);
}```
welp it has no errors anyway lol
This sounds like it has nothing to do with UnityEvents, Singletons, or Coroutines and everything to do with using Invoke
Invoke isn't used. Maybe somewhere under the hood of UnityEvents or Coroutines?
Oh wait a second
The tools I use use invoke
Thanks!
Im reading all assemblies, getting all types, finding exact match by string UnityEngine.Light, using the found type in GetComponent(Type type) and it doesnt find the component
my guess is that im getting something from legacy assemblies instead, meaning i have to skip it when gathering types
is there any read on which are actual final dlls?
hm but the weird thing is im getting them all already and only finding one UnityEngine.Light type, id get several if there were duplicates right? how would that even work
ah no nevermind i xy'ed myself
Why on earth would you search assemblies for strings to do this
user input
Is it possible to call ParticleSystemRenderer.BakeMesh on the job system?
Looks like you were looking for .Select() it allows you to do
List<string> completedQuestId = activities.Where(x.type == "QuestComplete").Select(x => x.refId).ToList()
Hey guys, trying to implement some Collide and Slide stuff into a character controller, has someone a nice ressource for this?
Saving the texture of the MeshRenderer
Hey everyone. I don't quite get how do I use Bson in new versions of unity(editor says it's obsolete and has a separate package but I can't find any new solutions or this package).
SaveData data = new SaveData();
SavePlayers(data);
using (var stream = new FileStream(CommonPath, FileMode.Create))
using (var writer = new BsonWriter(stream))
{
JsonSerializer.CreateDefault(null).Serialize(writer, data);
}
I found this code that should save data as binary but it saves it as regular json with some weird characters and the file even weights more than a regular json save file.
While we're troubleshooting Json stuff, does anyone know why it's returning "Null" for name? Am I using the deserializer incorrectly?
{
"name": "Sebastian",
"Characters": {}
}
StreamReader sr = new StreamReader(path);
string json = sr.ReadToEnd();
sr.Close();
wd = JsonConvert.DeserializeObject<WorldData>(json);
Debug.Log(wd.name);
is there a way for a NavMeshAgent to automatically change the mesh/surface it is baked on without having to place hundreds of bridges at the ends of all my chunks?
without seeing the class itself its hard to tell
Standby
public struct WorldData
{
public string name { get; private set; }
public Dictionary<string, CharacterData> Characters { get; private set; }
}
hello everyone im new to c# and i need some help with my project , i want to make an app in unity that pulls notifications(like whatsapp ,messages etc. ) from an android phone and send it to my arduino through a bluetooth module , i have done the bluetooth part but i dont have any idea how to recive notifications using code.Please mention or dm me if you can help ,thank you in advance.
is the dictionary also null? i dont see any attributes
is it opt in/out?
Uh... let me try to fill it with some default data and see
any help with my nav issue or do I just have to place the bridges everywhere
you mentioned chunks how large is the world?
navmesh already has tiling built in which optimizes large worlds
procedural world
you dont need to keep separate navmehses
its procedural, so i do
you plan to simulate the whole world at all times?
no
then usual approach to this is to update the mesh at runtime around the player
well, one of the approaches
that will work?
yes with NavMeshComponents
each chunk has its own surface
the problem is monsters stop at the edge of chunks because they dont switch navmeshes
i understand the problem, and i dont have an immidiate solution, apart from maybe hacking around with the agent by disabling and pushing to another mesh then enabling
problem is path itself
rn my solution is placing hundreds of offmesh links at the edge of every chunk, which causes the creatures to be jittery near the edges and takes a ton of time to set up
ill see if I can try and bake at runtime maybe
Seemed to have resolved it. I think it took issue with the private setters
you added attributes?
{
"name": "Seb",
"Characters": {
"Sebastian": {
"id": "0",
"name": "Sebastian",
"credits": 10000
}
}
}
thats the json itself
youre using newtonsoft json?
Yes
By default a type's properties are serialized in opt-out mode. What that means is that all public fields and properties with getters are automatically serialized to JSON, and fields and properties that shouldn't be serialized are opted-out by placing JsonIgnoreAttribute on them. To serialize private members, the JsonPropertyAttribute can be placed on private fields and properties.
theres probably a setting somewhere that lets agents cross meshes
idk as long as it doesn't stop at the edge of the chunk and stand there awkwardly
infinite?
at any one given moment? Because it is infinitely generated, just not at the same time
navmesh tiling allows you to rebake an arbitrary area at runtime
ok let me look at that
so if you opt for player centered mesh, you can bake only those areas that are in the bounds of the loaded chunks
this means you will have to periodically recenter and rebake the whole thing starting from player chunk outwards
but even given the large size of it you are still only computing loaded chunks
i assume you already do world shift
origin shift
yes
the world generates from the player
or the generation gets the players position and generates the world around it
so each time you shift the world you can do the big rebake
and when new chunks encountered you do only them
so what would I attach the navmeshsurface to?
i have a feeling you dont do origin shift
No i think i do
you have to shift the whole world towards zero once the player reaches around 2-3k units
void GenerateFromCenter()
{
for (int x = -2; x < 3; x++)
{
for (int z = -2; z < 3; z++)
{
bool Occupied = false;
foreach (Chunk c in Chunks)
{
if(c.coords.X == x+Center.X && c.coords.Z == z + Center.Z)
{
Occupied = true;
}
}
if (!Occupied)
{
GenerateChunk(new Coords(x + Center.X, 0, z + Center.Z));
}
}
}
}
//Check if the player is far enough away to spawn new chunks
void CheckDespawn()
{
foreach (Chunk c in Chunks)
{
if (DifferenceInCoords(PlayerIn.coords, c.coords) > 3)
{
if (c.gameObject != null)
{
Destroy(c.gameObject);
}
}
}
}
ohhhhhh
no i dont do that
heres the generative part of the generation script
when you get to the shift, just incorporate the rebake into it, and youre good
ok so
which object is doing the baking
some static class in the api
so do I stop attatching a navmeshsurface to each chunk?
woah
uh
should all the chunks be children?
your player will essentially only ever move around the zeroes, while the rest of the world shifts under him
how you implement it i dont know, the parenting will probably be worse than just iterating over chunk roots
because any parenting incurs transform hierarchy update cost
alright ill figure things out
i advice to just keep track of chunks and agents and move them by iteration
that will be much faster
I can just cut the object in the original counter, the duplicated one doesn’t work😳
If I just put an object in the duplicated counter, nothing works
you provide the bounds with NavMeshData struct
yikes its not struct
yikes its not even the correct one
UnityEngine.AI.NavMeshBuilder.UpdateNavMeshData() there we go
ok ill look there
theres an async version as well
Apparently block keeps turning out to be null and giving me an error. Why?
and I have checked prefab, it's not null.
https://gdl.space/lohubejami.cs
Exact error:
NullReferenceException: Object reference not set to an instance of an object
TerrainGeneration+<LoadWorldCoroutine>d__80.MoveNext () (at Assets/TerrainGeneration.cs:1375)
Line 1375: block.transform.parent = this.transform;
hmmm what do I use for the data param for updatenavmesh
where do you assign block nvm
what does SpawnObject do?
nope
then right click -> go to definition or something
he just sits there at the chunk endge
ok wait
what if
big brain time
I attatch an offmesh link to the front of the monster
all that i was suggesting was based on the idea of a single large navmesh
ohhhhhh
so that method would update an area of it
lots of small meshes
yeah
ok
ill try that
yoooooooooooooooooooooooooo
I got it fixed
I just need a bridge in front of the monster
Hey again. Can I still use Bson with Json.Net? It says it's obsolete and I don't think I quite understand how it works
No idea.
sup guys, does someone know how I can make the missile (only move forward) to start with same rotation and direction the player is?
I've tried:
void Start()
{
transform.rotation = player.transform.rotation
}
void Update()
{
transform.Translate(transform.forward * speed * Time.deltaTime);
}
transform.Translate(transform.forward * speed * Time.deltaTime); is wrong, since Translate works in local space.
transform.Translate(Vector3.forward * speed * Time.deltaTime); would work
hmm let me check
that is assuming you don't already have a problem in your Start function
but Vector3.forward isnt a fixed global coordinate?
Translate works in local space
so itd be "forward in local space"
which is what you want
the object's forward direction
Vector3.forward itself is not implicitly belonging to any coordinate space.
yep that's why I dont understand, because Vector3(0,0,1) should move in the global Z
it worked
thanks
hmm, so I guess Json isn't that good for storing large quantities of data(like positions and variables of all items dropped in the game), is it?
but still doesnt understand why it should be a fixed value xD
I would use a more efficient encoding for massive amounts of data, yeah
but then again
i wouldn't really worry about it until i wound up with multiple megabytes of data
ok, thanks
I’m currently trying to make my player’s position persist between scene transitions. I want it so that if I enter a different scene and then go back into the previous scene my player is in the same place. I have this script that I use to transition between scenes: https://gdl.space/oyunilazef.cs. The purpose of this script is to allow the last visited scene to be loaded. I also implemented two methods in my player script to save the player position into PlayerPrefs: https://gdl.space/ifebihiwuf.cs. The issue with my code in the SceneChanger script is that the part after the scene is loaded in the LoadScene method does not run after the scene is loaded, which is what I want it to do. I was doing some research and found out that Unity has an event called SceneManager.sceneLoaded that is called when a scene is loaded: https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html. However, I have never used events in Unity before and I am not sure how to go about implementing logic to load the player’s position when a scene is loaded. Is anyone able to help me out?
hey, silly issue. im trying to initialise a material as green, and the material itself is green, but when i put it onto a line it just displays as white
when i change the colour manually, it works fine, the only issue when initializing the lines with code
gridMat.color = new Color(128, 255, 128);```
```line.material = gridMat;```
new Color(128, 255, 128) this is white
Color uses 0-1 values
ohhhh ok
You can also use Color32 which uses 0-255
perfect, thanks!
Is it possible to make a prefab based on other prefab?
I have prefab Child without any links to other prefabs. I want to create empty Parent prefab add make it base prefab for Child, then apply some of the components of Child to Parent.
yes they're called prefab variants
I know what prefab variant is.
I'm asking how to change non-variant prefab to variant prefab and set up base prefab for it, after I already have child prefab.
Well I know in newer versions of Unity there's a way to re-establish a prefab link from an object in a scene
not sure if there's a similar mechanism for prefab -> variant
Well... you "can" go the manual route and just change the YAML yourself.
I know we were forced to do that a few times a few years back at work.
would it not just be easier to have the player "Don'tDestroyOnLoad"?
thus the position stays the same
That might be a good idea, I might try that
I probably have to much stuff on "Don'tDestroyOnLoad" 😄
How can I stop Json from adding junk to my floats?
what junk?
-8.67 turns into -8.670000076293946 in json
Do you have some guides on how to do that?
This is just a consequence of floating point binary representation.
8.67 cannot be stored accurately in a binary floating point number.
Is there a reason it matters for you?
It has nothing to do with JSON
I mean, for large quantities of data this can take up a lot of space, can't it?
no
ok then
floats take up 32 bits of space no matter what
that's neat
The number 1 takes the same amount of space as this
thanks
Well. It can. It the json it might be problematic.
Isn't JSon stored in strings though
true in json it takes more space
didn't realize you were saying that
but it's still a string while stored on a drive
Yes as json - if you care you can format the number to a limited number of digits
Ou. I mean. If your meta files are stored as text. Its not that problematic.
You can probably reverse engineer it.
Its just about assigning an ID to some field eg... parent_prefab_id or whatever.
But this might get you started.
but how can I do it, I give a limited number of digits and it extends it
I believe the decimal data type is what you are looking for.
Its just about seeing if your json serializer understands it properly.
Do you think storing a decimal would result in shorter numeric strings?
I don't see how it would
Or would it? Less imprecision?
Well. Its gonna take up more bytes in memory but it will be shorter in the json. (or at least it will get rid of the imprecision)
Problem reading .obj file
@wide pecan are you using Newtonsoft.JSON?
Now I'm using JsonUtility but can switch to Newtonsoft
Yeah that makes sense. Not sure if I have seen a decimal in a json, does it look the same as a float?
I have some json files that could probably reduce their file size by 30% by doing something like this
It looks like Newtonsoft might have an attribute which can be used to specify serializers, and one such serializer for this purpose:
[JsonConverter(typeof(RoundingJsonConverter), 4)]
public float myFloat;
But I've not tested it
Edit: possibly only on properties - unclear https://www.newtonsoft.com/json/help/html/JsonConverterAttributeProperty.htm
Edit Edit: looks like you may need to implement the actual converter yourself still :/
I mean. Introducing custom serializers/deserializers is way too much work for a 30% size reduction.
There have to be lower handing fruits for optimization like that 😅
Now if you were sending vertex data as json or something crazy like that.
With milions of vertexes. Then sure I guess.
See, it depends on the case
Damn I keep forgetting that optimization is a curse word here
But serialization/deserialization should happen outside of gameplay. Hidden by a black screen.
The answer is always something like "its not worth it" without any context
I mean. Damn. I just remembered the story about GTA5 loading being cut by like 60% by a guy optimizing their JSON 😅
I think ive heard of that, wasnt it a random guy?
Yeah. A "modder" that got angry at how long it took I belive 😅
That dude went vigiliant lol
Ok so I added DontDestroyOnLoad to my player's start method but now when I go back into the scene with my player there are two players. How do I fix that?
oh, wait, Newtonsoft handles vector3 values much worse, now it adds Magnitude and sqrMagnitude parameters and also normalized values, this takes up a lot of space
Only if you make a custom serializer
Lol, Newtonsoft isnt that superior after all is it?
What's the best way to make a system where enemies not in view are disabled? Stick a trigger on the camera and run something like GetComponent<IProximityHandler> on every colliding object? Maybe OnBecameVisible?
OnBecameVisible is my first thought
there are a bunch of checks and complicated stuff you can do to try and fix it
what I do instead is this...
What if I want to add some padding to make it more natural?
using UnityEngine;
public static class BootStrapper
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Systems")));
}
named BootStrapper.cs
If you use OnBecameVisible then the only "adjustments" you can make are the bounds of the renderer
I'll try it
inside my resources folder is an object with the things I want to always be "Don'tDestroyOnLoad"
idk how the script works exactly...but it isn't on anything but it initializes that only once when the game starts
So I don't have to attach this to anything? Do I need to call anything in my DontDestroyOnLoad objects?
nupe
that script just runs once by itself when game starts and puts the "Systems" object that is in Resources folder into Don'tDestroyOnLoad
I named it systems....doesn't have to be called that
code name and object name need to be the same tho
How do you create that object?
And that folder should have prefabs of all the other DontDestroyOnLoad objects as well as this script?
Ok, I've tested and having 500 saved items only takes up 35 kb, so rounding their position isn't that necessary here
Does OnBecameVisible get called on disabled behaviours?
I have 1 DDOL object that has children on it that I don't want destroyed
if you didn't just want 1 main object with others as children you would need to drag all prefabs into the resources folder
public static class BootStrapper
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Systems")));
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Player")));
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("gamemangera")));
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("etc")));
}```
Not sure, docs dont say anything, try it out? 🤔
easier to just put all DDOL on one prefab and call it once imo
@sage latch Just a FYI there's a bool isVisible also if you ever need to poll it instead of the OnBecame messages
https://docs.unity3d.com/ScriptReference/Renderer-isVisible.html
Yeah I saw that, but it does require a renderer which one of the objects I want this for does not have, makes me wonder if the OnBecame messages also need a renderer to work.
Ah, well yes you do need a renderer
I'm thinking maybe you can use a "dummy" renderer that isn't really visible but gets detected by camera?
Basically just use the bounds of it
Yep, without messing with the bounds of the visual
Sounds reasonable
@sage latch Lemme know if it works
Doesn't work on disabled ones :/
Guess I'll have to disable the components one by one
Maybe have one script that is always enabled, and it listens to OnBecameVisible/Invisible
yes
And that script would have a List<Behaviour> or something
And then enable/disable those behaviours accordingly
Well, having it on a separate script was the plan all along Composition > inheritance 💪
Osmal
in the end I decided to just store position as vector3 with all 3 values being floats multiplied by 1000 and rounded, this way json doesn't add any junk because now they are just like integers. When instantiating, I just divide the position by 1000
I added the script to the root of my Assets folder. The "Systems" prefab is there as well. I am getting an error. Here is the error and my prefab.
The child prefab has link to the base, yes. But I can't just change it because child prefab stores only modifications of prefab. So i need redefine all components of my prefab and still somehow connect it to this "modifications" structure.
Doesn't look like "not problematic" to me, it's the same rebuilding of all prefabs as with manual recreation using ui.
Or am I missing something?
Sometimes these hacky workarounds are the way to go 😄
and from 190kb 2000 items now take up 127kb
screenshot of full code and Systems location
using UnityEngine;
public static class BootStrapper
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Systems")));```
Screenshot is coming
Hehe thats pretty much the 30% that I approximated
Ok, I'll try that
Ok it worked but it created two players. I deleted the Systems from my scene and that created one player but it broke my Cinemachine follow camera since it references the player object
you can either put the camera inside your dontdestroyonload also
or code on camera to find player
Well another problem I have is that there are some scenes where my player isn't present, i.e. menu and UI scenes. What should I do about that?
other solution...don't have player in don'tdestroyonload, and just store its previous position in a gamemanager before moving to next scene so you can give it the old position in new scene
I just disable the player during that
if you change player looks/armor/weapons etc...its better to be dontdestroyonload imo
Ok. I'm going to try a few things then
(code wise its not that hard to find player in scenes 👌 )
if i have 1 method that is supposed to be abstract, should i make entire class abstract or just make method virtual?
You can't have abstract members in a class that's not abstract, so that option is out
i know
so leave method abstract and just add abstract before class name, or make method virtual
Okay, so ask yourself the following question:
Does it make sense to have instances of [your class]? Or is it intended to only instantiate child classes of [your class]?
it's the second
Then, mark the base abstract
private void OnCollisionEnter(Collision collision)
{
ContactPoint[] contactPoints = new ContactPoint[collision.contactCount];
int contactCount = collision.GetContacts(contactPoints);
Vector3 avgNormal = Vector3.zero;
foreach (ContactPoint cp in contactPoints)
avgNormal += cp.normal;
avgNormal /= contactCount;
if (avgNormal.y > 0.95f) //ground
{
Debug.Log("Added " + collision.transform.name + " to groundCollisions.");
groundCollisions.Add(collision);
return;
}
}
private void OnCollisionExit(Collision collision)
{
ContactPoint[] contactPoints = new ContactPoint[collision.contactCount];
int contactCount = collision.GetContacts(contactPoints);
foreach (Collision gc in groundCollisions)
if (collision.Equals(gc))
{
groundCollisions.Remove(collision);
Debug.Log("Removed " + collision.transform.name + " from groundCollisions.");
return;
}
}
I spawn on the ground,
console prints Added floor to groundCollisions. as expected
I move up to a wall
console prints nothing as expected
I move away from the wall
console prints Removed wall from groundCollisions. which is not possible in my opinion
if (collision.Equals(gc)) #<- because of this part here
{
groundCollisions.Remove(collision);
Debug.Log("Removed " + collision.transform.name + " from groundCollisions.");
return;
}
how can the collision equal the one in the ground collection if they are colliding with two completely different objects as shown by the console?
is it just that the Collisions are a non comparable type?
comparing their transforms yields the same results
also, note that the groundCollisions is a HashSet<>
How do I rotate a pre-existing quaternion an amount of degrees about a variable axis?
this only seems to return a post-operation value, how would I add this to another quaternion?
transform.rotation = Quaternion.AngleAxis(30, Vector3.up); damn it even has an example
i think they literally mean add though
yes, and I understand that part, the problem is that you cant add quaternions
That doesnt rotate an existing quaternion though
yea i missunderstood
AngleAxis can still be used here, you can combine rotations with * operator
Im trying to calculate object orientations before they become transforms, so quaternion math is something ill have to famliarize myself with
The only math operators you need to know is the Quaternion * Quaternion that I mentioned and also Quaternion * Vector3 to rotate a vector
And all the helper methods: LookRotation, FromToRotation, AngleAxis, etc
epic
Hi - is converting between quaternions and euler angles fast or not really? Compared for example to calling transform.rotation
previously I was generating transforms by having a parent and creating children in it's local space, but im planning to ditch that hierarchy for more stable rigidbody simulations :)
I'll be doing it a lot and idk if I need to optimise it
a lot - I mean thousands per frame
They aren't exactly cheap operations
I have seen Internal_ToEulerRad or whatever pop up in my profiler every now and then
Especially when doing procedural animations/active ragdolls
Im trying to generate a car, so I only need to do these operations once so that I can force objects to remember their original relative orientation.
they weren't replying to you oops
quaternion multiplication isn't expensive generally
so don't worry
That will probably affect your performance. Use the profiler with deep profiling mode to find out
does anyone know why my code behaves the way it does?
the post above these convos, I can reply to it
OnCollisionEnter/Exit isn't really reliable. You can exit one collider but still be in contact with a previous one.
I mean it's reliable in doing what it does
Im looking a bit more into it hold on
yes I'm aware of that, but the if statement seems to be behaving weird
like, how can that be true if they are two different collisions?
yeaaa, thought so
I have a bit of a problem then
because I will need to do a ton of calculations on rotations (either eulers or quaternions) for my machine learning project
adding noise to it, to be specific
Basically what I'm doing is reading a list of rotations/positions from a file, then every frame setting a ton of copies of gameobjects to that data, but each copy gets some (different) noise added to it
and I'd like to squeeze out preformance, as much as I can, I'm hoping to train my agent overnight :/
I have never used Equals with a collision, seems a bit sketch
Hmm do you have this enabled perhaps?
https://docs.unity3d.com/ScriptReference/Physics-reuseCollisionCallbacks.html
Anyone know how to deal with Cannot build player while editor is importing asset or compiling scripts
I used that one because == had the same outcome lol
I'll check that out brb
I dont think comparing collision works, i was just trying it and i never got it to even remove my terrain from collision exit
I even tried comparing their transforms (which are different as tested by the Debug and proven in the console)
AFAIK if this is enabled then it will sort of "pool" the Collisions?
Which could lead to a reused collision to be the same object as in a different collision
I set it to true and it still behaves the same
I don't think it's a physics issue tbh
I have no idea what is it though
click around in your editor if there is no loading bar, or if there is, wait for the loading bar to finish
it'd be nice if I could debug the HashSets themselves
Set it to false, I was just thinking maybe it was true
Why dont you store Colliders instead of Collisions though?
it works now
I'm just afraid what does this mean in the long run
What made it work? 🤔
because I need the collision information, not collider information
setting Physics.reuseCollisionCallbacks to false
Wasnt it false to begin with?
Or it was true?
it was true to begin with because that's the more optimized way
less work for the garbage collector
Makes sense that it fixed it then
it'd be awesome if I could set this value to be false only for my player and everything it touches
because the enemies and everything else won't need that luxury
The doc says it reuses one Collision if its true
and well, if I have alot of entities walking around and colliding that just sounds like a lot of collisions to sort through
Keeping a Collision object alive for longer than the collision message method seems sketchy to me anyways
I'll try to think of another way
but if I don't think of sum else, this still works, so thanks
Don't store a list of Collision, use a custom struct with the data you need
Collision has a bunch of cruft you probably don't care about
well the actual reason is really dumb
What data are you currently using from the stored Collisions? I see only transform
it's cheaper to compare collisions
than to create a new vector
run a loop to get an average of all the contact point normals
and then compare that average vector to a stored one
because I really only need the average vector of the collision
foreach (ContactPoint cp in contactPoints)
avgNormal += cp.normal;
avgNormal /= contactCount;
Debug.Log(avgNormal);
if (avgNormal.y > 0.95f) //ground
{
Debug.Log("Added " + collision.transform.name + " to groundCollisions.");
groundCollisions.Add(collision);
return;
}
this is what decides if the collision gets added
which is fine because it's necessary
You just reminded me of this extension method I wrote years agocs public static Vector3 GetAverageNormal(this Collision col) { var count = col.contactCount; var result = Vector3.zero; for (int i = 0; i < count; i++) { result += col.contacts[i].normal; } result /= count; return result; }
Now that I look at it, its kinda garbage
I should at least normalize the result
foreach (ContactPoint cp in contactPoints)
avgNormal += cp.normal;
avgNormal /= contactCount;
I would have to also have this in the exit too
which isn't terrible but still
ayo 
we both wrote the same one 