#archived-code-general
1 messages · Page 320 of 1
no they cant, Program Files should never be used for user data
I don't want it in the documents as it can get in the way. It's like how VTube studio works
you can use Application.persistenDataPath or streamingAssetsPath
I think I found how to do it from docs using a web request and 'file://'
how do u all animate ur charactrs
I change the image used on the go. Probable not the best
indeed, I was just about to suggest that
I think the sprite render is broken lol
What's wrong?
It's off target. You can see where it should be (green box)
I this problem as simple as having the camera be the child of an object that moves during fixedupdate?
if so, why wouldn't the camera position be jittery even while not rotating?
Is there a way to automatically destroy particle system object when all particles disappear?
Can do it manually based on particle lifetime, but wonder if there is a better approach
particleSystem.IsAlive
I don't need to check if it's alive, think it will be better to use lifetime instead of checking isAlive every frame.
I asking of some mechanism like an event that is invoked when there is no particle left, or some auto destroy. Does something like this exist?
Legacy ParticleAnimator had autoDestruct (https://docs.unity3d.com/560/Documentation/ScriptReference/ParticleAnimator-autodestruct.html) property, that does exactly what I need, but it's obsolete now. Do we have something like that now?
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.
make one
Ienumerator fireondead()
yield return new WaitUntil(() => !particleSystem.IsAlive);
DoSomething();
better idea. Don't check and estimate by a lifetime you set at the start
you don't always need to destroy the system asap. Let it disperse and linger then destroy
But I would need courutine for this and this logic controled from a non-monobeh class
so what?
why wouldn't you just use a stop action? https://docs.unity3d.com/Manual/PartSysMainModule.html
I can't run coroutines from non-monobeh classes right?
this is what we call 'programming'
You take the pieces that you have available and you put them together in a sequence rthat does what you want
I do, but I don't want hundrends of stopped particle systems hanging around
not as such, but that does not stop you starting a coroutine on another monobehaviour
What do you mean, hundreds of stopped? I'm saying set the stop action to, for example, destroy the ParticleSystem's GameObject
should be requeueing them if you're generating tons of them anyway
Oh, I misunderstood you. Thanks, that what I need
Hey, I'm using the StarterAssets 3rd person controller and whenever I use their prefab to unpack and swap only the meshes everything works fine, the character walks normally. However if I try to setup a character with a different setup (other skinned mesh renderers etc) the character walks suuuper slow.. Both are tagged as humanoids on the imports, have about the same height
What could be causing this issue? It was caused by the animator Apply Root Motion
this dosent appear to work. ive tested and i cannot use the force adding part, it just goes on its own
and it goes in more of a square, not a circle.
oh and once it gets to the last point it resets which i think i can fix
I have a observer pattern that notifies (from the GameController) when a level is completed. I have two Singletons subscribed to that observer, one is the GameDataController (that manage all the data and it save and loads it ) and a ProgressBarController (that updates some objects on the UI to let you see your progress and fails). The ProgressBarController does a Get to the Instance of the GameDataController¿If the notification is send at the same time how can I do to ensure that the info that is read from the progressBarController is the last info?
have GameData notify the ProgressBar
Or should I just change my structure and unlink the ProgressBarController from the GameController and add other observer on the GameDataController that notifies the ProgressBarController? I just prefer to have all on the GameController to reduce the cohesion
Nop, the GameController notifies progressbar and gamedata. I'm trying to avoid that GameData notifies so it makes it easier if you want to change the way your info is storaged
if you have a race condition, then they both cant be subscribed similarly, so the idea is the one you want to be notified first will then notify the next object itself
unless you can define the execution ordering with events, but I'm not too sure about that
Try changing the FixedUpdate() on SplineFollower to also uses forces instead of just setting the posittion. In this way the object will be receiving some different forces to move and to stay on the spline. Something like this:
void FixedUpdate()
{
t += Time.deltaTime * speed;
Vector3 targetPosition = CalculateSplinePosition(t);
Vector3 moveDirection = (targetPosition - transform.position).normalized;
rb.AddForce(moveDirection * speed, ForceMode.Force); // Adjust force as necessary
}
so i dont need force applier anymore?
Yeah, thank you for helping me to clarify my ideas. I will use the concatensted notify. Adding it with a Interface, so every GameController should add it obligatory
Yes, you need both, one that apply the force to move it forward and backward and the other component to apply the force to ensure your object is following the spline
well, it works but it dosent snap to the spline
Maybe there is a propper way to to that but I don't know much about that, sorry I can't help more. Hopping someone with more knoledge can help you
ah oj
if you care about the latest one you should be able to "drop oldest"
Thank you, i will consider it.Good that I studied concurrent and distributed programming, but i forgot almost everything about it since I haven't use it frequently
There’s also an implementation of it from cysharp on the UniTask repo
How would you implement the structure of the snake, which can move in the different directions and is affected by the gravity, although its rotation always stays the same?
Every 1x1 block represents the part of the snake's body. The number of the blocks can be changed. This way, adding 1 block to the snake makes its tale 1 block longer
I consider having a parent empty GameObject with the Rigidbody2D component, and the blocks with the BoxCollider2Ds
Just a list of Vector2Int
I'm referring to its structure #archived-code-general message
It's Unclear what you mean by "structure"
The way the object should be built in the game
Does having various BoxColliders work just fine, or is there a better way to implement this?
Use multiple boxes with a CompositeCollider2D
Got it, thanks
you can use OnCollisionEnter2D(Collision2D collision)
First get the collision point with "Vector2 collisionPoint = collision.contacts[0].point;"
next you get collider's center point "Vector2 colliderCenter = collision.collider.bounds.center;"
next calculate distance between point and center "float distanceToCenter = Vector2.Distance(collisionPoint, colliderCenter);"
compare the distance "if (distanceToCenter < cornerThreshold)
{
Debug.Log("Player hit the corner of the collider.")
}"
float cornerThreshold = 0.1f; (you can adjust this threshold)
hey, how can i rewrite this in a way that lets me build the game?
use Resources.Load
AssetDatabase is Editor only
Or Addressables.
ffs another 'doesn't work'. Explain please what doesn't work
Ok, so what path are you using for Resources.Load? And please go and read the documentation as well
right, just found that the path has to be relative to the resources folder
will try with that
not just that, please read the docs carefully
yeah, no extensions
it worked, thank you
Aye you're reaching you're limit.

It does get a bit much when the only explanation you get for a problem is 'doesn't work' and that 500 times a day every day
Yeah true that.
Anyways. I'm wondering if there's something that exists with these characteristics:
- Globally accessible fields like a singleton or static.
- Fields accessible and serialized in the editor and can reference assets like a scriptable object.
Here's how I've done this...
using UnityEngine;
public abstract class SingletonSO<T> : ScriptableObject where T : SingletonSO<T>
{
private static T _instance;
// only really needed for the editor when Domain Reload
// is disabled.
public static bool InstanceExists => _instance != null;
public static void ClearInstance() => _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = Resources.Load<T>("SingletonSO" + "/" + typeof(T).Name);
_instance.OnLoad();
}
return _instance;
}
}
protected virtual void OnLoad()
{
}
}
you can ignore the InstanceExists and ClearInstance parts if you have Domain Reload enabled
I use those to look for the singleton and get rid of it when the game starts
It will look for an asset by name in a Resources folder
There is another way using Reflection trickery but that is not for the unwary
e.g. Resources/SingletonSO/MySingletonType for a class called MySingletonType
I use this for "catalogs" of other assets
I use something similar for prefabs, too.
Yeah that makes sense.
Seems like using Resource is about the way to go.
I found Unity localisation while trying to find other ways.
I was originally planning to do this with Addressables
but nothing else in my game is using Addressables, so it was not a good fit
this is not a code problem
zoop
Real.
can someone please help me my unity editor wont download it just keeps "validating"
does anyone know how to fix this?
this is still not a code problem
Btw, SingletonSO are used for storing sounds to use with id system for example right?
Just looking for some use cases. 
But I do have the feeling directly referencing something might limit me in some ways.
is there a reason you can't directly reference the sounds you want?
either the AudioClip itself or some other asset
No I'm just looking for use cases.
I did remember some people dumping all their sounds into one library.
Most of my SingletonSOs are either:
- the root of a hierarchy of assets (e.g. the root Settings category)
- a service (e.g. a class that can give you an icon that matches an InputBinding)
some are also just a bundle of references that I need in many places
that would be annoying (and error-prone) to manually assign
I need to write a validator to make sure I'm not missing any singleton assets
get all children of SingletonSO -> try to load each one
Ur hub is drinking weed and it's probably hanging. Maybe close it with the task manager and retry, if it happens again, search on Google.
this kind of thing makes big changes a lot easier to handle
i can automatically check if any of my entity prefabs have a missing reference
i couldnt find anything
Ask on #💻┃unity-talk
i did and they gave me answers that didnt work
you also ignored my last request, so...
And that makes it a code problem, why?
its not i js wanted help
we have different channels here for a reason, you ask your question in the correct chanel and, maybe you will get an answer
well i didnt in the other channel
you certainly wont here
How to create visual effect graph? I don't have an option from the screenshot. Do I need some package installed for this?
unity 2021.3
It's a package, yes.
Found it, thanks
just a simple question i wanna gather some experience working in a team is there any place where i can collab with people
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
also, not a code question
You may be interested in #🕹️┃game-jams for that kind of thing, though
which would be more appropriate than those forums, which would be for specific projects
thx
Craeful they will threaten to ban you for writing your own code over your own lol
I almost got banned last week for saying I don;t use Coroutines and have my own time based functions and I don't see why to use them
Scroll up man seriously actually happened
ok
Link it
Because I see this
#archived-code-general message
Where you were almost banned for being off-topic like you are now. Not at ALL for saying you don't use coroutines
Asking why use Coroutines is off topic?
It's all the other whining and nuisance stuff. Not the asking about coroutines.
If you asked in a non-confrontation non-childish way, it would have been fine
And now you are randomly dragging it up again to whine more
Like this?
#archived-code-general message
Come on...
whats with Unity people thinking coroutines are normal thing in every negine most engine don't cripple while loops? I did I simply asked why use coroutines I don't see how they are better then writing you own time based functions?
they jumped down my throat to the poiin ta mod said I had to tell him that I lvoe Coroutines
I think it was more a case of I know best because I live in a city where other people make video games
no, you filled the channel with garbage and a mod had to get involved to make you stop
as you are doing now
nevermind
they jumped down my throat to the poiin ta mod said I had to tell him that I lvoe Coroutines
Objective lie
I have screenies
I read it all. Everything you've said about it is a lie.
This channel is for getting help and giving help. (Even saying it was a week ago. That was yesterday...)
Not for whining
Please stop
Complaining about people is
Ill report discord to Unity because we are sick you guys BS tons of forum posts about how mods run this place it's like a bunch of 15 year olds in here thanks
please leave, child.
no ban me
So you want to go around saying "they banned me for asking about coroutines"
When it is really that you are being a nuisance and attacking people for no reason? Gotcha. Best of luck with that pitiable behaviour
okay. <@&502884371011731486> obvious troll
That's really silly. And most of the people you've talked to are other developers, just like you, not mods. That must be saying something.
when you described getting banned from another server for some kind of deltaTime-related argument, I got a very clear picture in my mind of how that went down
I can just imagine this server being run by 15yo's. 99.9% of posts would be idk and wdym
We need a name for this archetype: maybe „Passive aggressive learner“
!warn 436401905392943105 Don't spam the channel with off-topic. Read #📖┃code-of-conduct
mouse8763 has been warned.
let's not contribute to the spam further, and end this
Hi yall, just need some confimation on how the child gameobject works, when a child gameobject gets destroyed in runtime, the index of the child gameobject remains right? if so how do I remove this empty index so a new instantiated child can take its place?
Destruction happens at the end of the frame.
A useful trick is to set the child's parent to null before you destroy it
This gets it out of your list of children.
You may want to insert the new object with SetSiblingIndex before you destroy and unparent the old object
Ohh this is incredibly useful thankyou.
Anyone knows how to get transform rotation values that are > 90 ?
What does it mean?
👀 uhm you can enter a number as large as your want
Actually, I wonder whether Euler clamps it
No, it's better to say "converts"
idk actually
It, probably, should
I want to write
spring.targetPosition = angle```
Angle should be targets transform. Rotation. X value
Why would you set the target position to a rotation?
Target.localEulerAngles.x returns values upto 90°
More than 90 it' starts decreasing the output
Well, yeah, because 100 deg equals to 80 deg
So it simply starts going down
I wasn't sure about it, actually, that's why I said "I wonder"
What exactly do you want to achieve though?
using UnityEngine;
public class SetHandSpring : MonoBehaviour
{
private HingeJoint joint;
public Transform target;
void Start()
{
joint = gameObject.GetComponent<HingeJoint>();
}
void Update()
{
JointSpring spring = joint.spring;
var angle = 0f;
angle = target.localEulerAngles.x; // Right
spring.targetPosition = angle;
joint.spring = spring;
}
I have a hand
It has a rigidbody, hingejoint and box collider.
And I have a seperate "target" Game object
I want to calculate the targets x axis angle, and add that angle to my hand objects hingejoint spring value.
I have explained here
Haven't worked with joints before, but JointSpring doesn't even contain the definition for targetPosition
Unless it's your custom class you're using
Ignore that
This should thus throw you an error
What?
Ignore the joint part
My issue is with the "angle"
How should I gather rotation.x value as it shows in the inspector
The same way you do it right now
It doesn't seem to be wrong
Oh, you have a 3D project, don't you?
Yeah
Then you also have 3D objects?
Yeah
{
if (joint == null || target == null)
return;
JointSpring spring = joint.spring;
float angle = target.localEulerAngles.x % 360f;
if (angle > 180f)
angle -= 360f;
spring.targetPosition = angle;
joint.spring = spring;
}```
Hey thanks
Will try and update you guys
They're saying that it doesn't go higher than 90 deg
Still, I wonder whether eulerAngles can ever return a value, not clamped within -180 and 180
it can
I see
But eulerAngles will return you the same value within 0 to 360 range.
However if you will rotate object in script, unity will keep values in editor within -180 to 180 range.
Sorry didn't work
Same result
If in inspector I give rot.x value as 85
Output is 85 from localEulerAngles.x
If I set 90
Output is 90
If I set 95
Output is again 85
Is there anyother way to do this other than euler angles?
then you can use Quaternion and then transform Quaternion to euler
Could you elaborate please?
{
if (joint == null || target == null)
return;
JointSpring spring = joint.spring;
Quaternion targetRotation = target.localRotation;
Vector3 targetEulerAngles = targetRotation.eulerAngles;
float angle = targetEulerAngles.x;
if (angle > 180f)
angle -= 360f;
if (angle > 90f)
angle -= 180f;
else if (angle < -90f)
angle += 180f;
spring.targetPosition = angle;
joint.spring = spring;
}```
try this
Will try sure thanks
if that doesnt work try to remove
angle -= 360f;
if (angle > 90f)
angle -= 180f;
else if (angle < -90f)
angle += 180f;```
this part and see what you get
This didn't work
Sorry this didn't work either
Ideally use Quaternion.AngleAxis if you're working 3D
But I need the angle value
I have one object
And I have a hand object with a hingejoint that has a spring parameter
I want to assign the rot.x value to the spring value of the hand object
well, start debugging and seeing if your values are correct step by step. Dijabola has given some ideas
you still haven't shown what the scene looks like. i'd really like to see how things are arranged
An image that shows the target object, as well as how it rotates
make sure it's on "Pivot" and "Local" up here
Yeah they are on pivot and local
Ok sure
Just a sec
The red one is the "hand"
The white one is the "target" Name as left shoulder
Based on the left shoulders (target) x axis rotation
The hingejoint ,spring target position, of the "hand" will be assigned
and you need to measure how far the shoulder has rotated around the red axis in the second image?
Yeah
Rotating the object around the red axis changes all three X/Y/Z euler angles
Thats fine
but that means reading the local X rotation does not tell you this. it tells you something else (whose meaning i'm unsure of)
So if I can provide the x axis angle here
It will do the rotation of the hand for me
Localeulerangle.x is giving x rotation valye
But only till 90°
Is there any other way
You would rotate an object?
For eg I have 2 objects
If I move on object in the scene through inspector
I want the other object to copy and rotate similarly
Is there any way to do that?
so you want the hand to behave like it's parented to the shoulder?
Yeah
But parenting it won't work
It will already be parented to the body
the hinge joint already does this: as I rotate the parent object, the child spins around it
I can't parent it to the target
The cubes are siblings. That's just how a hinge joint works
oh
that recorded nothing, oops
Yeah
I can't parent it to the target
Parented to the body already
Hmmm
But that's not what I am looking for
If I rotate target
The hand should rotate equally
Is what I am looking for
Is there any other way I can track angle change?
I don't know what this means. The second cube is following along with the first cube.
I need to see an example of the movement you're trying to create, because I don't understand what it is
ah, okay, you are rotating the shoulder around the axis of the hinge
so you need to update the hand joint to try and match that
I need to create a inventory system. My plan is to go through this in steps. The first step is to create a scriptable object to store item data. Currently I have a scriptable object that stores upgrade data, but I am going to have multiple kinds of items, not just upgrades.
The upgrades are little computer chips that you can find in buildings. What I want to do is make an inventory system so you can pick the upgrades up and choose which ones to use on the radar. But I also want the player to be able to find other types of items like food and water.
How can I go about creating a scriptable object that holds item data, while also being able to hold extra data from upgrades?
figuring out joint rotations is a bit of a pain -- I'm still kind of unclear on the math involved. I did find one thing that might be useful, though
void Update()
{
var spring = joint.spring;
spring.targetPosition = -joint.angle;
joint.spring = spring;
}
wait, actually, why not just set it s target position to zero?
(this does something similar, but it's much more wobbly)
target position of the spring from hingejoint?
joint.angle is the angle between the two rigidbodies (relative to how they started)
right
targetposition of the spring is 0 at first
i need to increment and decrement it based on the Targets x rotation value
If everything is supposed to fit in one inventory, the food water and these upgrades, then the only thing to do really is make them all either implement a common interface or inherit from an abstract item class.
does anyone know how to write a script for unity that interacts with the verticies of a mesh? Like if I wanted to try to create a softbody physics script. Or do I have to learn how to write shaders to do this?
@heady iris Alright, I'm a bit confused. I have 2 scriptable objects called UpgradeSpec and ConsumableSpec. I have a single non-monobehaviour script called ItemData. How do I store the data unique to each upgrade or consumable?
technically you can just modify the vertices of any mesh dynamically at runtime. It doesn't matter whether those modification yield softbody physics or something else. You will however likely find yourself without any generic way to implement softbody physics that perform well.
If ItemData is a non-monobehaviour script then I can't create more than one version of it. So, how can I store information unique to each item if I can't have multiple versions of this script?
Are unity events reccomended to be used? Such as:
Something like where one script has:
OneScript.cs
public static event Action OnButtonPressed;
public void AnimationFinished() {
OnButtonPressed?.Invoke();
}
and another script will do something when that action is invoked such as
AnotherScript.cs
private void Awake() {
StartButton.OnButtonPressed += StartGame;
}
private void StartGame() {
for(int i = 0; i < 4; i++) {
SpawnCard(i + 1, (Card.Suit)i + 1);
}
}
those are regular c# events, whether usage makes sense depends on your project.
oh good to know
I've heard things that they are like resource intensive but I just wanted to ask if they are like reccomended
Unless you are subscribing/unsubscribing thousands of times per second, I wouldn't worry about it.
JacksonDunstan.com covers game programming
relative to burrito's comment
JacksonDunstan.com covers game programming
that article seems to conflage memory allocation and garbage
technically its only garbage if the memory gets released. Typically "garbage" is memory allocated repeatedly for single use which is then "discarded".
C# event basically creates new array every time you subs/unsubs so that’s that
UniRx could be alternative
how does that solve allocations?
It will reuse allocated slot on frequent subs/unsubs for starter
I would recommend you at least cleanup the event
by cleaning up you mean unsubscribing?
indeed
okay i see
I usually do
OnEnable() event += method
OnDisable() event -= method
I feel like it's a linked list and not an array.
Nope it is an array
anyeone know how to stop my pixels in a pixel eprfect camera to stop turning grey from a perfect white. they keep blending togetehr for some reason
What is the problem why it becomes null
TMP_Texts are not null
same thing happens even if don't put conditions or if(occurrence==null{ occurence=this} in awake
I used Start instead of awake or both same error
which is line 65
first one
objective completed comment
it is pickup gun system
then ObjectivesComplete.occurrence is null
it becomes null idk why
well you probably have more than one of those components, so when the second one runs Awake it assigns null to the occurrence variable
also that else if isn't comparing to this it assigns to this (though that is not related to the current issue)
This is tutorial#67. In this course you will learn 3d game development step by step using unity game engine by developing Third Person Shooter TPS zombie apocalypse and zombie survival horror game.
Follow us on our Instagram: https://www.instagram.com/wits.gaming/
Complete Course YouTube Playlist: https://youtu.be/tSkKIqvDTEM?list=PLA-xaldQ72r...
5:54 he does same thing
no error
but in comments there are a lot of guys getting same error
the error is due to the issue i just pointed out in the ObjectivesComplete class
not due to the line of code that is being written at that time stamp
should i use empty object for this static class
this is a code channel mate
and add something like dontdestroyonload
this is also irrelevant. did you even read what i said about the code?
how can I control Awake priority if it is static class
i mean unity does that
it is not an issue with the priority of Awake
you literally assign occurrence to null if it isn't null
your singleton is set up incorrectly
i did other things too same errors are coming
wdym you "did other things too"
then this is likely an issue with the order your code runs in. do not access the singleton until Start at the earliest
I get it
It is about setactive() thing
when parent object is gone it automatically becomes null
set active will not make that variable null. only destroying the object after it has run Awake will make it null unless you explicitly assign null to it somewhere
I made two gun object one is on sofa other one is on player hands
sofa was active and i shared its codes
player hands are inactive
when you press key it activates that
and other one is inactive
that is all irrelevant
but now it worked
i used that error line in hand gun
when you first use with awake
it worked
this time
hard to explain without video but i solved
what part of "do not access the singleton until Start at the earliest" do you not understand?
How can I prevent clicks from deselecting UI buttons?
EventSystem.current.SetSelectedGameObject(FirstSelectedButton);
I use this to select a button when I open specific UI object, but clicking outside causes it to lose that object and I have to left click + hold over an object(but release outside it so I don't click it) in order to "fix" the issue.
The game will use controller to play either way, but it would be nice if I knew how to avoid this type of issue in general.
Eh, maybe need to catch the user clicking outside and set back the selected gameobject
Is there another way? This seems kinda hard lol
So this is meant to send "OnDeselect" to a previous object after you select a new one, so it snot exactly what I want, but maybe it works.
The problem is that I'd have to create a script for those buttons which I dont really need/want.
getting away with unity ui and utility without scripting is wishful thinking
It is preferred to have only 1 EventSystem in the scene right?
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.EventSystem.SetSelectedGameObject.html
Why would you have an override to give this function a pointer to an event system then?
It's not required, but its not explained why would that be needed.
it's just an optional parameter it looks like
which probably defaults to current event system
pointer has a type of EventSystems. BaseEventData
Not EventSystem
Missed that, still not sure what it does.
It’s to pass how game object is selected. i.e. mouse click event
That’s why it’s named pointer
As in mouse cursor
Got it
I am trying to find a way to Get currently selected button with this method:
EventSystem.SetSelectedGameObject
I tried .currentSelectedGameObject but it returns null
After 2nd try, it seems to be selecting it properly now 😮
I'm quite new to using Animations to trigger things like attacks. I want to know if I would be piling myself into technical debt if I use animations to trigger attacks. Instead of using code to do so 
Not sure what do you mean by that, but your game logic should be handled by code most likely.
whats stopping you from using code to do so?
Im not a fan of animation events myself, it is a complete pain in the ass compared to just syncing up something to happen when you want it
I have a Coroutine that can be launched via the StartCoroutine method, and different classes are activating this Coroutine. I have another method that stops the Coroutine.
If a different class other than the one that started the Coroutine tries to stop it, I get this exception in the console:
"Coroutine continue failure"
I did research on this. This doesn't actually cause any problems, it just generates the error. The workaround is to make sure that the same class that started the Coroutine also needs to be the same class that stops the Coroutine. But the problem is, I won't always know which one is going to stop the Coroutine.
I don't want to have to implement interfaces or make things more complicated that it currently is to work around this. Is there an easier way to prevent the error or ignore it?
well save the coroutine-runner with the Coroutine variable 😄
Alternatively have a dedicated object that runs coroutine so you can always call thru that object
On your first suggestion, I believe I'm already doing that. but I think your second suggestion will work.
I like it. I'll try it, thank you.
Im getting this error with no stack trace, is there something specific that causes it?
I have a Character poco which i made serializable temporarily so I could see it in inspector. Theres really nothing special going on with it. https://gdl.space/vulemakepo.cs
The error doesnt seem to affect anything, but its just annoying to see.
Can someone very smart explain the difference between Manhattan and Euclidean distance? I get that they produce different values but surely, when using them for pathfinding, the values are gonna still be in the same order of smallest to largest regardless of which distance you use?
it might need a parameterless ctor
the error is somewhat random and doesnt always happen, but I will see if that solves it
so euclidean distance is the distance you would get using the pythagorean theorem, where it's the shortest possible path from one point to another. manhattan distance is like distance on a chessboard where you basically just count how many squares it takes to move from one position to another
this is kind of an oversimplification, but should help you understand how they are different
Okay but surely on a grid, they'll still produce the same order of smallest distance to largest?
Like, I don't get the difference when applied to A*
It might have a different meaning in the context of the algorithm. Might want to share where specifically you're reading about it
It's a background explanation for my diss. But I can't think of an algorithmic difference between the two
it should but because euclidean distance is the straight line between two points, it may underestimate how far two positions are, especially if you are using grid based movement where you can only move on one axis at a time
its really just a difference of what heuristic values you are providing
heuristic has to be the value where no real solution is shorter
hey, i'm trying to use physics2d.istouchinglayers to no avail and i'm not sure why. i've looked through online forums and documentation, but i can't seem to find a solution.
colliders in question: circlecollider2d and polygoncollider2d
both colliders are on the same layer
any help would be greatly appreciated.
It's a different ratio when compared to the G cost right?
I mean, that's what makes sense in my head
Ok so I forgot that A* works with G+H, I was thinking about how the H values are still in the same order but when G is added, they're not necessarily
its been awhile since ive studied these, but honestly the difference in what the algorithm does for your A* doesnt matter. The heuristic should simple give the largest value it can while never ever overestimating. If manhattan or euclidean works better here than use either one
there are papers on what the difference results in even
https://docs.unity3d.com/ScriptReference/Physics2D.IsTouchingLayers.html
It is important to understand that checking if Colliders are touching or not is performed against the last physics engine update i.e. the state of touching Colliders at that time. If you have just added a new Collider2D or have moved a Collider2D but a physics update has not yet taken place then the Colliders will not be shown as touching. The touching state is identical to that indicated by the physics collision or trigger callbacks.
go through this to troubleshoot: https://unity.huh.how/physics-messages
"Give the largest" huh? In pathfinding it estimates how the remaining distance to the target
this might be a dumb question but i don't need a rigidbody on either object for it to work, right? also, the objects i'm trying to check are not moving in a manner where the last physics update makes a difference
yes an ideal heuristic gives the largest value it can, while never overestimating. that while is important here.
You could have a heuristic simply return 1 for everything, this is useless
you do because it's the same conditions as a physics message per the documentation
Why the largest? Manhattan distance won't give you "1" for all cells all the time
Surely it's just THE value it predicts
the heuristic is an estimation. if you had THE value then you wouldnt need a pathfinding algorithm at all because you would already know the best path.
different algorithms give different results, thus the best heuristic gives you the largest value, the most accurate value. Think of it like this, you are told to walk to the nearest park. Before leaving you ask one person how far it is, they say 5 minutes. You ask another person, they say its 10 minutes away. The park is 15 minutes away in reality. The 2nd person gave you a better answer, both were underestimations but one was closer.
now if one person said 20 minutes, this would be bad.
Oh, the biggest out of all heuristics? Ok. Though, I didn't know heuristics had a rule of never being too big
well if it were too big, then you would be overestimating the distance and the algorithm wouldnt work
Yeah well if you applied Euclidean distance to a grid where you can only move up, down, left or right, it would underpredict surely?
Ignore that hang on
brain whirring
yes, manhattan would be better there
if you had a grid where you could move in 8 directions, manhattan would overpredict and is useless
Ahh I see I see
See yh, I forgot the size of the number mattered. I thought the only thing that mattered was the size in relation to the H values of other cells
Forgot it's G+H, not just H
Thanks
so i need a rigidbody on at least one of the objects involved for any detection of touching to occur?
yes, the touching state is identical to the state reported by OnTriggerEnter2D and OnCollsionEnter2D. you can go through this to help set up your objects to ensure they will report the correct touching state:
https://unity.huh.how/physics-messages/collision-matrix-2d.html
https://unity.huh.how/physics-messages/trigger-matrix-2d.html
dang
is there any way i can detect whether a collider is overlapping with something else without having a rigidbody on it?
a physics query like an OverlapCircle or something like that
Why do you need to not have a Rigidbody
What are the [SerilizeField] thingys called? Like the part where you do the [].
attributes
Ah, thanks!
I'm still having this issue if anyone has clues. #archived-code-general message , error "Unsupported type Character" with no stack trace. I added a parameterless ctor but its still happening.
🤔 Ive seemed to narrow it down to a specific object in my scene, a target dummy who if I delete (and undo deletion) get more errors. Guess this isnt an issue with the code then.
I would guess this is a meta data problem. you could try deleting the meta file of any object that uses Character and let Unity rebuild it
im a bit unfamiliar with what meta files actually contain, is there any drawbacks to this? or will it all build back the same
you will just use the existing references which you will have to re assign
Where is the usage of this class?
i see
a component, CharacterBehaviour, creates instances of Character and then really its used everywhere. There are 92 references to Character itself.
its probably my fault because Character used to be the monobehaviour, which i renamed to CharacterBehaviour. Then created a poco Character.
Ah then it sounds like meta issue sure
Your GO probably has that old reference
When you rename class file make sure you rename meta as well
you might even need to delete the Library folder as you may have a corrupt AssetDatabase
Just delete that meta
I renamed it through VS, compiled, and then made Character later but idk. Ill try library if I get the error again because at least i can recreate it now
AH, wrong, I never rename stuff in VS
Rider automatically rename meta, but not all IDE does that
If you rename in Unity it will be rename meta as well
indeed
damn didnt know that, Ive been doing this a lot and its the first issue ive had. I even suspected this might be an issue, but figured it was fine if i let it compile first
if you didn't have so many references I would say delete it and add it back but I guess that is not an option
since this is just the poco i can delete it, its not actually used in inspector. i just have it serializable so i can easily see what characters my enemies are trying to target
oh you meant the monobehaviour probably
but if you delete it you will get compile errors which will mean Unity wont update the Assetdatabase and meta files
i see, well worst case ill just remake the target dummy because im fairly certain this is only an issue with that one object
Don’t you have something like "script cannot be loaded" in your GO that has problem?
i think i did see something like this before
ill have to deal with that later though, something else in my project has gone really wrong 👀
Yeah if you see that you can remove that script and add back (Or use debug inspector to swap script)
so apparently i just needed to go into the prefab itself and remove the script that couldnt load. even though the version that was in my scene didnt have this problem...
somehow along the way i also had a major issue with newtonsoft which involved deleting it as a package for it to recognize as a namespace. im too tired and confused for this right now
Definitely sounds like a meta data fuck up
thanks both for the help
np
I didn't know where else I could post this so pardon me if this is the incorrect channel.
I currently use Unity Version 2022.3.22f1 (also had same issue on 2022.3.5f1 and 2021.3.12f1 across multiple projects).
I have not been able to make a proper build at all the last week or so. I keep getting failed build attempts with similar errors relating to this same Library\Bee\artifacts... file path. In this case, I am trying to make a WebGL build but I've had similar build fail errors with Windows builds as well. The only exception was when building using the Mono scripting backend for a windows build. I have had a hard time trying to figure out whats up and would appreciate anyone that has some insight.
what does the error say?
i wonder if there might be more detail in the full editor log file?
How do I access that editor log file?
it is extremely long. Would linking the whole thing fine?
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ObjectivesComplete : MonoBehaviour
{
[Header("Objectives to Complete")]
public TMP_Text objective1;
public TMP_Text objective2;
public TMP_Text objective3;
public bool obj1comp = false;
public bool obj2comp = false;
public bool obj3comp = false;
public static ObjectivesComplete occurrence;
private void Awake()
{
occurrence = this;
}
public void GetObjectivesDone(bool obj1 = false, bool obj2 = false, bool obj3 = false)
{
if(obj1 == true && obj2 == false)
{
objective1.text = "1.1: GOREV TAMAMLANDI";
objective1.color = Color.grey;
obj1comp = true;
}
else if(obj1 ==true && obj2 == true)
{
objective1.text = "1.2: GOREV TAMAMLANDI";
objective1.color = Color.grey;
obj2comp = true;
}
else if (obj1 == true && obj2 == true && obj3 == true)
{
objective1.text = "1.3: GOREV TAMAMLANDI";
objective1.color = Color.grey;
obj3comp = true;
}
}
}
This static occurrence still becomes null
where is the problem
this error comes from another class that uses this static class' function
when i use debugging, it doesn't even come to static's awake
What here is line 37?
Please share your !code using a paste site
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I mean there is not complicated command
only calling
still becomes null
Try logging ObjectivesComplete.occurrence at the beginning of the start method of ObjectivesComplete and Rifle
Also, is occurrence possible assigned anywhere else?
I checked out didnt find, only command calling nothing more
Do you have an active object on the scene that has ObjectivesComplete as a component?
Well yes, Awake will never run then
Yes
The whole point of components is having them on game objects
Then forget the logging part, just assign the script to a new empty gameobject specific for this
Then I should create some empty object where it has static component
and others access that
like gamemanager
If this is weird and you don't want to assign this on a game object, then just use a normal class and assign this in the constructor
Yes they can, that's what the static field allows
I will use this system on another objectives completed messages changes
like 1) some mission info => use static to change text | new 1) you completed
Sure, but I would reverse the logic and have the manager change its own data
I tried making this system
Have it subscribe to events rather than allowing outside behavior modifying its state
The latter is just messy and unreadable
I couldnt get used to using events,interface and ienumerable yield systems but i can try
I know they are really useful but
Yes i solved problem it is really about inactive gameobjects
you should always use always active gameobject for static
Events are not hard
Just write one for whatever object would otherwise update the UI and have it be a meaningful event
Like if an Enemy would update some "alive" counter, just make a "died" event and have an UI manager subscribe to that in order to update its counter
I need to be comfortable to use them like using void function(parameter 1,parameter2)
Need to make 5-10 example about it
hey guys can anyone help me, trying to make my car controler turn, but its not working, well, it is and it isnt, itsd resetting its y position to 0 but not turning over time like it should be... ive included images as well to help, but i dont know what im doing wrong there is a ridgidbody on the car so that it has physics ands everything but i dont get why it isnt turning.
void Update()
{
Child = this.gameObject;
//Debug.Log(Child.name);
localrot = (float)Child.transform.rotation.eulerAngles.z;
//Debug.Log(localrot);
angle = this.transform.rotation.eulerAngles.y;
if( localrot > 290 || localrot < 70)
{
//Debug.Log(rot.y);
if (Input.GetKey(KeyCode.W))
{
this.transform.Translate(Vector3.forward * Time.deltaTime * speed);
if (Input.GetKey(KeyCode.A))
{
rot = (new Vector3((this.transform.rotation.eulerAngles.z),(angle * (Time.deltaTime * TurnSpeed)),(this.transform.rotation.eulerAngles.z))); // figure out why this isnt setting the rotation correctly.
Debug.Log(angle);
angle = rot.y;
Debug.Log(rot.y);
Debug.Log(angle);
Debug.Log("while going forward and the A key is pressed");
Quaternion deltaRotation = Quaternion.Euler(rot);
m_Rigidbody.MoveRotation(deltaRotation);
Debug.Log(deltaRotation);
//this.transform.rotation = Quaternion.Euler(rot.x, rot.y, rot.z);
it dont need to be anything fancy just while im holding down the a or d key it needs to turn in that direction, and well the other direction when in reverse
Configure your !ide first
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
i have already....
Your screenshot suggests otherwise
A properly configured editor would have correct syntax highlighting
Please configure it properly first to avoid unneeded mistakes that are easily handled by the editor
better ? it was just my text colour style....
cool, do you have any idea why its not working though?
@thin aurora you still there man?
ive been trouble shooting this for the lest 2 days please just help me out. just throw me the correct docs or something please! i know you cant give me the answer but please just give me a hand
Hello i tryed to make a good Smooth Camera that you can turn with keycode right MouseButton pressed but its not Smooth and very wird can someone help me?
using UnityEngine;
public class MovementController : MonoBehaviour
{
// The speed at which the player will move
public float speed = 5.0f;
// The sensitivity of the camera rotation
public float rotationSensitivity = 10.0f;
void Update()
{
// Get input from the horizontal and vertical axes (WASD keys)
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Create a Vector3 object to store the direction we want to move
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput) * speed;
// Check if the Space key is being held down
if (Input.GetKey(KeyCode.Space))
{
// Add an upward movement component to the movementDirection
movementDirection.y += speed;
}
// Check if the Shift key is being held down
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
// Subtract a downward movement component from the movementDirection
movementDirection.y -= speed;
}
// Move the player in the direction we calculated
transform.position += movementDirection * Time.deltaTime;
// Check if the right mouse button is being held down
if (Input.GetMouseButton(1))
{
// Get the mouse's x and y position
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
// Create a rotation vector based on the mouse input
Vector3 rotationVector = new Vector3(mouseY, mouseX, 0) * rotationSensitivity;
// Rotate the camera around the x and y axes based on the input
transform.Rotate(rotationVector);
}
}
}
Sorry, I'm working. I only occasionally check this chat
What does rot log?
there is so much wrong with your code it's hard to know where to start.
- Never readback eulerAngles. It will not give you the values you expect.
- Do not mix Rigidbody and transform movement
- Rigidbody movement/rotation should be in Fixed Update
rot is just short for rotation, im only logging it to try and see its output to see what is going wrong.
how would any of this fix the issue of it not turning though,,, i dont understand.
its rotation is always snapping to 0
ill try changing the transform roation to the ridgid body rotaiton but i dont think it would fix anything.
Did you read point 1) ? Your whole code is based on an incorrect premiss
but eulerAngles works for other parts of my code with checking its x and z rotation, why cant it be used for its y rotation, is it due to how its outputting? i know its a little weird but surly if it outputs it like that it knows how to convert it back to a normal angle? right?
Do you mean me?
No, that is the incorrect premiss, when converting from Quaternion to Euler you can never guarantee consistency
no sorry.
ok
ah i see. so instead of euler what do you suggest i use?
you can use Euler but you must maintain the values yourself, yon can use those values to convert to Quaternion for setting the rigidbody rotation
yes but as thats what im trying to do, how do you suggest i fix this issue as this is about all i know, i tried useing transform.rotation.y but its just kept outputting 0 even when y wasnt 0.
because rotation is a Quaternion so rotation.y is meaningless
As I said start with an Euler value in your script. Modify that value as you wish during your script and convert it TO Quaternion to set rotation
ok sure, but how would i modify it, what am i even ment to do there? i dont understand.
sorry if this is frustrating, but i dont get how you want me to modify it.
you are getting Input values, surely that is enough to know how you modify the angles?
Hello i tryed to make a good Smooth Camera that you can turn with keycode right MouseButton pressed but its not Smooth and very wird can someone help me?
using UnityEngine;
public class MovementController : MonoBehaviour
{
// The speed at which the player will move
public float speed = 5.0f;
// The sensitivity of the camera rotation
public float rotationSensitivity = 10.0f;
void Update()
{
// Get input from the horizontal and vertical axes (WASD keys)
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Create a Vector3 object to store the direction we want to move
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput) * speed;
// Check if the Space key is being held down
if (Input.GetKey(KeyCode.Space))
{
// Add an upward movement component to the movementDirection
movementDirection.y += speed;
}
// Check if the Shift key is being held down
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
// Subtract a downward movement component from the movementDirection
movementDirection.y -= speed;
}
// Move the player in the direction we calculated
transform.position += movementDirection * Time.deltaTime;
// Check if the right mouse button is being held down
if (Input.GetMouseButton(1))
{
// Get the mouse's x and y position
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
// Create a rotation vector based on the mouse input
Vector3 rotationVector = new Vector3(mouseY, mouseX, 0) * rotationSensitivity;
// Rotate the camera around the x and y axes based on the input
transform.Rotate(rotationVector);
}
}
}
what just add or subtract it from the euler value? surly as youy just said that its not consistant i wouldnt get a consistant result.
will you please stop flooding the chat and use a paste site
Bro im sorry i send this message only 2 Times now nobody is helping me. If you find thats annoving then im sorry
its best if you just wait untill steve is done helping me then post it otherwise its just gonna get swept away again
I did not say add or subtract and I do not have the patience to teach you basic angular mathematics
oke
Guess what? We do not provide help with AI generated code
what do you mean by modify are you talking about the def to modify an item e.g to change it, or are you talking about some specal chr im just not putting together ?
just tell me that so i can bloody google it
Proof it why it is genaratet code?
@worthy bobcat Read #📖┃code-of-conduct Don't post chat generated code. Don't spam same question over and over. And use paste sites when you do come up with a proper code to show
are you talking about this
transform.rotation *= Quaternion.AngleAxis(angle, Vector3.up);
the modify operator?
If i get banned with a good reason proof that its AI generated Code!
@worthy bobcat Again. Read #📖┃code-of-conduct and don't post off-topic
what I am talking about is this (sorry I got your code mixed with the other persons)
localrot = (float)Child.transform.rotation.eulerAngles.z;
//Debug.Log(localrot);
angle = this.transform.rotation.eulerAngles.y;
...
rot = (new Vector3((this.transform.rotation.eulerAngles.z),(angle * (Time.deltaTime * TurnSpeed)),(this.transform.rotation.eulerAngles.z))); // figure out why this isnt setting the rotation correctly.
Instead of reading the eulerAngles read them once in Start and then use them as the basis for all your calculations and keep them updated with the current state
well i mean i got past that issue, ive gotten it to be set, its just not sticking now.
sorry forgot to at you
Quaternion.y is NOT the rotation around the y axis.
you should not be poking around in the individual xyzw fields of Quaternion
oh, didnt know that, thught it would work the same but apprently not. how would i get the angle of the y rotation from the thing i just set?
you are still treating Quaternion properties as if they were usable values. They are not
First I want to ask you, is this 2D?
Why are you rotating around the y axis in 2D, is that on purpose?
its 3d
Why does it seem like you're using a Rigidbody2D?
Since MoveRotation is taking only a float here
Oh nevermind misread a little
anyway didn't you just answer your own question with this screenshot?
still? dam, it.
really though it would be like:
Vector3 forward = rb.rotation * Vector3.forward;
float yAngle = Mathf.Atan2(forward.z, forward.x) * Mathf.Rad2Deg;```
huh?
you talking to me about this one?
i dont understand why they arent useable.. 😭
because they are properties of a Quaternion and quaternions are magical black boxes which almost no one understands
because they just aren't what you want them to be.
"Why isn't this cat a dog???"
it just isn't
it was never intended to be
so basicaly i trying to rap my head arround a mythical legend that only the person that made it understands?
you got it
which is why we NEVER read Quaternions we ONLY write them
ok 😦
how should i go about this then? rewrite the turning code?
completely?
probably not a bad idea and just forget that Quaternions even exist except to give you a starting point for a Vector3
dam it. i think the worst part of all of this is that i was following someone on youtube and this is how they layed it out... ive just been editing it to try and bring it back up to speed from unity 2018
this really is a rabbit hole you should never have gone down
could you give me a hand by showing me at least how i should lay it out ?
Sorry, no, I'm out of here for the time being. But I'm sure there must be something about this on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
am i at least on the right track here ?
no because you're still looking at Quaternion.y
No
It's really not clear why you need that line at all
no no forget that just angle = (angle - (time.deltatime * turnspeed));
angle just being a float.
honestly people can spend weeks if not months writing and fine tuning code like this, I really suggest you find something on learn which kinda does what you want and go from there. It's the path of least pain
i tried using a premade car controler however the wheels ( even when set up the exact way they do it in the video) just explode and go flying accross the map.
yes its useing wheelcolliders.
then you did not do it exactly right, this shit is difficult to do and you really need to understand it to do it at all
ight, ill try again.
take it in very small steps. Try to get just one wheel working then extrapolate from there
you wanna know the stupid thing.
i just got it working
GOD DAM IT !!
I can almost guarantee that that will fuck up during game testing
honestly i dont really care its for a college fmp, it only needs to work once XD
XD hahaha
anyway, if good enough is good enough, go for it
cheers for the help man, XD, i mean i didnt get it done the way you wanted but hey f it, if it works it works, XD
now remember, never change a running system lol.
if it aint broke dont fix it XD
this is the way
DO YOU KNOW DE WAY, XD apprently not but hey
A quaternion is like a complex number, but with four terms instead of two.
The values are not angles.
(it really should have just been called Rotation)
You don't need to understand quaternion math to use rotations
just like you don't need to understand matrix multiplication to use transform.TransformPoint
Problem #1 Need help please something is not working right with an instantiated prefab it is causing particles to not look right which are a different prefab even.
Problem #2 It's causing lag as well I am guessing it's the performance issue that is causing problem #1 if someone can DM or thread and help thanks.
I am trying to create a card that spawns a unit on a tile.
i need help with code monkey's video about a* if anyone has seen it https://www.youtube.com/watch?v=alU04hvz6L4
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=alU04hvz6L4
🌍 Get my C# Complete Course! https://cmonkey.co/csharpcourse
🎮 Play my Steam game! https://cmonkey.co/dinkyguardians
❤️ Watch my FREE Complete Courses https://www.youtube.com/watch?v=oZCbmB6opxY
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/co...
to whoever has seen it, what does he do with the PathNode pathNode variable in the first for loop? it seems like he is just adding some values to each node for each cell but then he does nothing to the said nodes later? at least for the local pathNode variable
Oh go by your game preview in the editor resolution I usually put my UI scaler at 0.25 so it is biased towards width over height but adjust according to needs really there. So I set both editor window and game preview window equal so they are about square approx.
You can get current preview resolution from the stats in the upper right corner of the game window.
I don t know where to ask but made a github colaborate project and my friend can t open the project because ArtifacDb is locked somone has a solve?
Sounds like you uploaded your Library and/or Temp folder to Github, which is a mistake
I recommend deleting the respository and remaking it with an appropriate .gitignore file
Apparently my Unity thinks 1*3 is infinity
and what .gitignore should i get?
from where?
i found one online for unity and that was the only one that i had in the project
This is a good starting point https://github.com/github/gitignore/blob/main/Unity.gitignore
i already had this one in the project when uploaded
well you did something wrong then
Did your repo contain the Library folder?
Check
if it did, you had already committed it before adding the gitignore file
sorry but what repo means
Can we verify the library folder is actually the issue here?
repo...
repository
the thing you store and retrieve with git
the thing that your project is saved in
I wanted to calculate the density of an object, so I had to calculate the volume, which I did by using volume = colComp.size.x * colComp.size.y * colComp.size.z;, and fir tge mass I just used rb.mass.
If I Debug.Log(rb.mass) it's 3, like it should be,
if I Debug.Log(volume) it's 1, like it should be,
YET if I Debug.Log(density), which I calculated with density = rb.mass / volume;, it's, and I quote my Debug panel, "Infinity".
Why?
what is colComp?
Oh, reference I made to a BoxCollider, forgot to add that to the message
it is, i m pretty sure because he says that ArtifactDB is locked wich is in library so i guess that s the problem
sounds like volume was actually 0. Can you show the code including the log statements and what it printed?
Don't guess
just look
i m pretty sure
if it's there, I already suggested how to fix it
don't be "pretty sure"
look and be 100% sure
i m 100000% sure
Then your fix is here #archived-code-general message
thanks
Add meaningful logs.
Debug.Log($"mass: {rb.mass}, volume: {volume}, density: {density}");
Do this and show what it prints
density is 0 in start
You calculate density before setting volume
You're not setting density until you run the CalculateBuuoyancy function
Oh my fricking god I am a moron
By the way there's a cheeky/hacky way of retrieving the automatically calculated volume and density of a Rigidbody. You can do this:
float originalMass = rb.mass;
rb.SetDensity(1); // If we set density to 1...
float volume = rb.mass; // Then the mass that got set will equal the volume of all the colliders!
float density = volume / originalMass; // Here's our calculated density
// Finally, set the mass back to normal!
rb.mass = originalMass;```
(assuming that's what you were trying to do)
I dont know whats the problem is
Many, many things
The first problem you have, is your IDE is not configured
you haven't set your tools up properly for working with Unity yet. Get it configured
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Woah man you're a pro
Uhm Idk if that's what PraetorBlue meant too but you also have to create the roadSpawner variable first by putting RoadSpawner roadspawner; before the start function, because you have to define the class/type of a variable when creating it, like int x = 5; and then you can use x
Also you have to put () after SpawnTriggerEntered to turn it into SpawnTriggerEntered()
Yes all that but there's no point in fixing the code until they configure their IDE first
it will be a waste of time.
But yeah setting up your IDE helps with that tremendously
yeah
I made a very big quad procedurally and this material won't render on it, but the base material does. Is there a setting there that I missed to make it work?
Did you actually assign this material to the quad
Hey! Yes, here's the object in the inspector. When I change the rendering mode on the material like opaque I can see my quad. But the goal is to have the pattern I assigned in albedo display and it doesn't do that 😦 Also, the material works fine on other Meshes like the basic plane
Oh I think my procedural quad is missing UVs on the vertices and that's why all that is "rendering" is the transparent part...
I don't get what's wrong
you cannot refer to an animation clip in the animator like that. the animator does not support indexing, especially not indexing with a string. you should take a look at the Animator docs
anim is not a collection. I don't know what led you to believe it was
How can I make a box collider not attached to the body of the Game Object they're the child of ?
This messes up one of my key mechanics
well that's not really a code question. but if you don't want it attached to the parent gameobject, then why is it a child of that object?
Bc it needs to move with it
what does the word "Attached" mean to you?
Trust me, I've tried a bunch of stuff
Ok
So basically
It's the Box collider of the GO with the tag "Gun"
But if it touches an object, it acts as if it was "Player" that did
yes, that is what happens when a collider is a child of a rigidbody, it becomes part of that rigidbody's compound collider
what is the purpose of this collider
So how could I make that not happen while keeping it as a child ?
because i'm gonna go ahead and guess this collider should actually not exist at all and should just be a physics query instead
I use it like a raycast
Since I can't make that work for the life of me
(my code is way too messed up, holds with hopes and dreams)
maybe just make the raycast work properly
and get rid of this jankness
maybe ask for help with your raycast
I would have done so if I could lmao
classic XY Problem lmao
(Basically it's become messed up since another mechanic is really jank)
Ok the direct answer to your XY question is to put a kinematic Rigidbody on the gun itself
the real answer is to get rid of the collider and fix raycasting properly
Is there, like, no way to fix that without having to rework all of my code
That's probably a better way to ask it, sorry
Honestly it sounds like there wouldn't be that much code to rework
like 20 lines at most
yup
Yeah I know...
either way I think you should take a stand against yourself
and for once
instead of taking the janky path-of-least-effort
go back and fix it for real
Btw what's a kinematic rigidbody ?
(Maybe I should explain better, I use that collider like I'd use a raycast to easily have other GO detect when I shoot using it)
(But some objects, i need them not to interact if I shoot them)
(Taht's why it's such a mess)
OH WAIT I HAVE A SOLUTION
Super janky and dodging the problem, but it should work
(Creating a bool that activates while I shoot that deactivates the interaction)
a raycast or boxcast with a layermask to filter out objects you don't want to "shoot" would be much better here and wouldn't require a bunch of janky workarounds
It would also require to rework pretty much all of my gun movement mechanics sadly
And I'm in a jam so I can't
Tho I'll do that next time I encounter the issue
Surely you arent that far into any solution where you cannot just make a physics cast
A Rigidbody that is set to kinematic
how. are you using the collider to move the gun somehow? 🤔
Okay I'll explain but it'll be super long
So basically I'm creating a 2D game where you move your gun around you with the left stick
But I'm too dumb to make stuff properly
So I coded it to work with a pointer that moves super fast in a clamped area, put an empty that looks at it at all times and then puttin the gun as a child of it
But that's really jank and anything more done to it would probably make it crumble bc of how weirdly it messed the z axis
So a raycast just goes nowhere
And messes a lot of stuff
Which the collider doesn't
And it was also easier to implement for interactible stuff like buttons
So I went with that
Sounds like a nightmare but have fun
it is 🥲
based on this comment alone i'd bet you were using its transform.forward for the raycast which is why it goes nowhere because the Z axis is used for depth in 2d
Also some other stuff added to it that I barely understand
But yeah that's basically it
The gun is holding together with shit and glue
(tho I use Visual Scripting so I'm not uusing that but probably something similar)
Hey there pretty people! I used the SimpleWebServer to test a WebGL build locally on localhost:8017, how can I stop the server from running?
Sounds like a SimpleWebServer question
sorry 😦 I will look the correct channel
hello i'm trying to make my 2d character do an animation (A) when a key is pressed then come back to the idle animation when the animation (A) finish
Set an animator parameter when you press the key, make a transition to the animation when that condition is true, and transition back to idle with exit time
help
public AudioSource passosAudioSource; // Referência ao AudioSource para os passos
public AudioClip[] passosAudioClip; // Array de clips de áudio para passos
void Passos()
{
if (passosAudioClip.Length > 0 && passosAudioSource != null)
{
passosAudioSource.PlayOneShot(passosAudioClip[Random.Range(0, passosAudioClip.Length)]);
}
else
{
Debug.LogWarning("ReproduzirPassos: AudioSource ou AudioClip não foram atribuídos corretamente.");
}
}
i did it but now this is what happens
What are your transition conditions
I created multiple cameras in unity and I want to make a car simulation game but I'm facing this error:
d3d11 failed to create rendertexture (270 x 152 fmt 27 aa 1), error 0x8007000e
There is no ss of this error because my computer shuts down when I get this error
That "Flap -> Falling" transition looks like you've put the falling animation as soon as possible. It should play after the flap animation is done. Drag it to the end of the clip
like this?
yo how do i start a set of coroutines and wait for them all to finish, the number is not always consistent, I'm running the same coroutine each item in a list.
There should be one falling after flap finishes
there might be a smidge of overlap
but there should be only one at the end
In a coroutine, if you do yield return StartCoroutine(...) it'll pause the one coroutine until the new one is finished.
im running multiple Coroutines from this coroutine
private IEnumerator ClearBlocks(List<Block> blocks)
{
foreach (Block block in blocks)
{
//run a coutuetine "ClearBlock(Block block)" on each block only continue after all are done
}
yield break;
}```
like this then?
yes
There's not a great way to do this with coroutines. I guess you could increment a number when you start ClearBlock, then have it decrement the number when it's done
Actually...
actually nevermind i realized a better way to do this
i just put the logic from ClearBlock into a Loop foreach loop in a while loop;
the only problem is that this will run sequentially, not all at once
private IEnumerator ClearBlocks(List<Block> blocks)
{
const float timeOfClear = 0.3f;
float finish = Time.deltaTime + timeOfClear;
while (Time.deltaTime < finish && blocks[0].sr.color != Color.white)
{
foreach (Block block in blocks)
{
block.sr.color += Color.white * 0.8f;
}
yield return null;
}
yield break;
}```
like this i mean
ah, this doesn't do what you think it does
Time.deltaTime is the time the last frame took
There is a way to ask for the realtime since startup
which changes throughout a single frame
should be Time.time right?
Localization uses that to avoid spending too long per frame on a cleanup job
no, that's also constant during a frame
Time.time depends on the timescale and won't go up if unity is frozen for a while
this is what happens now
oh thats good actually im only looking for scaled time here
(and Time.unscaledTime still isn't the literal amount of time that has passed in the real world)
it looks like you're trying to prevent the game from hanging as you update a ton of objects
if so, you care about real-world time
oh no basically its just a block matching game this is the animation for clearing a group of blocks
ah, I see
if the player pauses it should pause the effect
and oops, I just saw the yield return null at the bottom. So it's one iteration per frame
yeah
i've added the code in case it helps
yeah
private IEnumerator ClearBlock(Block block)
{
const float timeOfClear = 0.3f;
float finish = Time.time + timeOfClear;
while (Time.time < finish && block.sr.color != Color.white)
{
block.sr.color += Color.white * 0.8f;
yield return null;
}
RemoveBlock(block);
yield break;
}```
updated code
I'm pretty sure this will shoot past Color.white and run for the full 0.3 seconds
Do you want the effect to fade the block to white over 0.3 seconds?
yeah or cap at white, oh can color values go beyond 1,1,1,1?
Color uses floats
Oh
You can do this:
color is basically just a vector4?
yep
Color startColor = block.sr.color;
Color endColor = Color.white;
float startTime = Time.time;
float endTime = Time.time + timeOfClear;
while (Time.time < endTime) {
float progress = Mathf.InverseLerp(startTime, endTime, Time.time);
block.sr.color = Color.Lerp(startColor, endColor, progress);
yield return null;
}
InverseLerp tells you how far along you are between two values
And then Lerp gives you a blend of two values
Theres a color lerp??? tysm
This will end with the color being almost white
but you're destroying the block right after anyway, so it doesn't really matter
yup
please
oh wait i pasted the wrong code here this was clearBlock Singular
but i adapted it to work in clearblockes all at the same time i think,
private IEnumerator ClearBlocks(List<Block> blocks)
{
const float timeOfClear = 0.3f;
Color startColor = blocks[0].sr.color;
Color endColor = Color.white;
float startTime = Time.time;
float endTime = Time.time + timeOfClear;
while (Time.time < endTime)
{
float progress = Mathf.InverseLerp(startTime, endTime, Time.time);
foreach(Block block in blocks)
{
block.sr.color = Color.Lerp(startColor, endColor, progress);
}
yield return null;
}
foreach (Block block in blocks)
{
RemoveBlock(block);
}
yield break;
}```
(all blocks are the same color so i get crab the startColor from the first in list
ah, that avoids the problem of having multiple different colors, then!
here are the screenshots
currently my team has 5000+ debug log statement inside the project, this is quite bad as we dont have any config to these debug logs, they will still execute during runtime when our app goes into production stage
we also cannot delete them directly as we need them during development stage, any good idea?
my idea is to override the original debug log code tho, but i need to check whether the debug log function is hidden by unity or not
maybe add
#if unity-editor
#else
to it
ok this is bad you cant override it
annnd it seems u cant modify it from assembly as well
what my debug log(error) needs
-
identical function like original debug
-
only can execute on editor
-
all built app cannot use it
You can use the Logger to disable logs when you make a build, enable them when your testing in Unity, maybe you can use preprocessors to determine if your in the editor as you have, to toggle .logEnabled: https://docs.unity3d.com/ScriptReference/Logger.html (you may have to scroll down on that page)
Additionally, you can hook into the Debug.Log event and handle the logging yourself: https://docs.unity3d.com/ScriptReference/Application.LogCallback.html, or if youd rather have more control over it, albeit more work on your part, you could build a wrapper, and do a refactor (in VS, Ctrl + R twice), for all Debug.Logs to use your wrapper instead
pretty new to unity, trying to use OnAfterDeserialize() on an inventory scriptable object to update the inventory display when the item changes. I can't directly access the item's sprite during serialization so I don't know how i can update it whenever an item is changed
the items are scriptable objects as well
ty thats way less work than making a whole new logger urself👍
wait wrapper is better
my game manager will not destroy and will last thruout the whole game process
i gonna do the wrapper there
I presume these are ScriptableObject assets you've created
OnAfterDeserialize will only run when the object is deserialized -- as part of its creation
If you want to be able to notify things when the sprite changes, perhaps you want to use an event
It sounds kind of weird to be modifying a SO asset at runtime though. Can you explain more about what you're doing here?
here's the exact error i get, UnityException: get_rect is not allowed to be called during serialization, call it from OnEnable instead. Called from ScriptableObject 'InventoryObject'.
this feels like an XY problem
not trying to edit the scriptable object, just get it's sprite component to update the inventory cell to the item's sprite
why are you trying to do this in OnAfterDeserialize?
just get the sprite out in the OnEnable method of the inventory cell
that'll probably do it lmao
pretty new to this
especially the serialization stuff
there's nothing serialization-related here
its using iserializationcallback reciever
well, there's no reason for it to be involved :p
ISerializationCallbackReceiver is there for situations where you want to set up data that Unity can't handle by itself
and those embedded functions are giving me the issues
I mostly use the interface for c# classes because you need mono for OnValidate()
Unity can't serialize dictionaries -- just lists. The example uses the callback receiver to glue them together right after the lists are set up by Unity
to "serialize" is to turn an object into data
and then you "deserialize" the data back into an object
You aren't doing this -- you're just grabbing a sprite from a scriptable object
if i create a new Logger, can i make it public static so i dont need to create object everytime
u know just like using it as Debug.Log
Why would you want to do this?
ok u cant lol
to be simple, i have a project that has 5000+ debug.log inside it, there are no configs to all of them and they will keep running even this app went into production stage
which is awful
so i want to do something , more like an override to it, to make the Debug.log only runs on editor mode, but not in any built apps
annnnnd ofc u cant modify the source code directly right?
debug log is also a static class, u cant override it directly
ive sent you the literal code for it
its not about modifying it, but if you wanted to create your own then just copy what you want and implement whatever else on top
Hey Everyone!
Need help solving a problem. My goal is to have the camera zoom in or out depending on how far away the player is to a centered position.
i want to lerp between 10 and 15. min being closest to center, and max being furthest posible away from center.
the problem is i don't know how to translate the distance between two vector3 positions into a float.
any help?
isn't the distance between two vector3 positions a float
how do i collaborate on a unity project on version 2023.3.28f1
This is a code channel, you'll need to setup some form of version control though.
ok just wanna share my solution after all of this
public class LogOnDebug : ILogHandler
{
public void LogFormat(LogType logType, UnityEngine.Object context, string format, params object[] args)
{
Debug.unityLogger.logHandler.LogFormat(logType, context, format, args);
}
public void LogException(Exception exception, UnityEngine.Object context)
{
Debug.unityLogger.LogException(exception, context);
}
}```
im now making a new custom logger function which will replace debug.log/debug.logerror , we dont have warning so we ignore it lol
i gonna replace all existing debug.log to this custom logger
i have a game manager that will guarantee to be instantiated and initialized before everything else
public Logger LogOnDebug = new Logger(new LogOnDebug());```
annnd ofc i will keep modifying my logger script
ok
You may be interested in ConditionalAttribute
It lets you remove a method call entirely if a preprocessor directive isn’t set
#if editor
#else```
something like these right?
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute
this, and you can use the UNITY_EDITOR symbol for it if you only want your logging methods to work in the editor
sounds better 👍
Howdy folks. I'm trying to improve my animation state machine for an RTS game and could use some input if anyone has time. Every 100ms each AI unit's update call determines which animation to play based on its current state. For most cases this is a single call to "fire" or "die" that in the animation controller transition automatically back to an idle state, or hang on the last frame, or loop. And that all works fine. Where I'm having issues is the walking animations. If walking, then every 100ms the routine calculates the direction of movement and calls myAnimator.Play("walk direction"); And it works reasonable well, except it will call this repeatedly and so the animation's frames restart halfway through depending on various factors. I don't see an easy way to only play it again if the animation is not the one intended.
I should mention the walking animations are all looped, hence why it doesn't need to be played repeatedly.
[System.Diagnostics.Conditional("UNITY_EDITOR")]
public void Log(object message)
{
Debug.unityLogger.Log(LogType.Log, message);
}```
lol ok thats not 5000+ debug logs
still hurts tho
Just cache the last requested animation and don't replay it if it's walking animation.
:nod: That was where I was leaning. Didn't know if perhaps the animation system had a flag for "don't let this play over itself" sort of thing.
can someone please tell me how to debug this. my game freezes when changing song ( entering circle trigger ) the first time and never again ( except for super rare occurance. it happens at run time and happens when i deploy full build.
use the profiler to see whats actually happening. probably something being loaded for the first time
By default I believe audio loads on-demand. So you'll want to have it preload audio. I've noticed lots of stutters since I started adding SFX for various things and am about to look into this myself.
@exotic aspen @lean sail this is what i found in profiler
Yeah that looks like something loading audio related.
@exotic aspen awesome. so it's not my code. thank god. i was about to panic with the amount of debugging i'd have to do.
Yeah check out that link and see if it works for you.
@exotic aspen fixed! thank you!
interfaces are not inheritance. the only methods on that interface are LogException and LogFormat so you aren't inheriting anything, and you have to implement those. anything else is implemented by you
are you sure the LogOnDebug object you are calling LogError on is that LogOnDebug class and not perhaps some other class that implements ILogger since that is the interface you would use for logging?
sry i copied the wrong stuff
i used Logger to instantiate it lol
Someon who wanna make a cool 2d game with me?
!collab 👇
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Damn thats crazy
how do I reference an Editor script from another script?
can you explain what exactly you are trying to achieve?
You should probably give more context. Referencing scripts depend a lot on how the scripts work in terms of number of instances, when they are instantiated and such
you can use GetComponent<script>() on the object with the script for most cases
not for an editor script
Again, depends heavily on the context
Maybe explain, why you wanna do that?