#archived-code-general
1 messages · Page 198 of 1
So a third object. Is the object in the scene before hitting play? Make a public field and drag and drop it. If not, I'll need more info. But once you HAVE the references:
if (thirdObject.valueICareAbout >= valueNeeded)
{
childObject.SetActive(true);
}
Dumb problem/question... I attempted to migrate my project from 2022.3.9 to 2022.3.10 but there was some package dependency error so I had to revert back to 2022.3.9. Works fine, but in the package manager I'm now seeing all packages labeled as "Custom", and I'm not able to update any of them. Any idea how/why that happened, and how to fix?
Ask in #💻┃unity-talk
This channel is just for coding
Will do, thanks!
I don't know though, just to be clear haha
im actually changing the prefab file
Then yeah, it won't reset
I assume you mean changing it in code, right?
yeh
Then yeah, that is expected behaviour
how would i stop it doing that then
Save the original value and change it back
change it back when on start?
Sure
Why are you modifying the prefab btw?
so it changes of all of the instatiated objects
Hmm, ok. Well I guess that's one way to do it 😄
is there a better way
Save the objects and change all the instances only. Or have them reference an object with the layer and subscribe to when it changes via an event invoked by the setter
how do u change all instaces
You save all of them when instantiating and iterate over the list you saved them in
Or
When instantiating, have them subscribe to an event evoked via a layer property setter, and when you change that property they will all set themselves
I would do the latter
ok so wait for the last option
Instantiate(genTube, cylinder.transform.position, cylinder.transform.rotation);
thats my code for instantiating them
You can do:
GameObject go = Instantiate(...);
then you use receive a reference to the instance right there
then you just have that instance subscribe. Maybe to an event on the object instantiating it, maybe to a singleton
so will that put them all as children of that game object
No, It will just give you a reference to the ONE object being instantiated
Instantiate has a parent parameter if you want to set them as children though
right ok let me try it out
that didnt work
I should also say, if you instantiate a component from the prefab you can get the reference to that component. So, like:
MyScript clone;
clone = Instantiate(prefabScript, ...);
then you don't have to do a getcomponent or anything
This is generally preferred, because you rarely need directly reference gameobjects (all monobehaviours can just call .gameObject to get it when needed)
does anyone know in which channel i can get help with GUID
there are so many channels
Depends on what kind of help. Coding with them?
thanks
hey, I have a unity ragdoll and its floating in the air, I have know idea what i should check for.
don't crosspost. also check #854851968446365696 for what to include when asking for help
My unity ragdoll is floating in one point in the air. Many of the limbs are rotating and turning like they should be but the center around the shoulders is not. I have tried enabling and disabling the enable projection box on the joint but none of it has worked.
Got it to work, for anyone else with this issue, your joint cannot have the "Connected Vody" set to the rigidbody on that gameobject,
Im trying to add default methods to some unity events using the reset method, and it works fine for events that dont have any arguments, but I can't seem to figure out how to give them an argument using the AddVoidPersistentListener method from UnityEditor.Events
private void Reset()
{
UnityEventTools.AddVoidPersistentListener(unHoverEvent, ClearHoverPrompt);
UnityEventTools.AddVoidPersistentListener(hoverEvent, SetHoverPrompt); //this method takes a string argument and gives me an error since there is none
}
You need to have a custom UnityEvent that takes a string . . .
Do you mean a UnityAction? Im not sure how (or why) you would give an event a parameter
Wondering if anyone could help me out with this. I have a Behavior tree and im trying to get the players location since I cant make a gameobject public and drag it in, in the inspector. Any way I can find the players location through regular code. I have tried getting the tag of the player on start within my attack node. But its just not working out. Im also using physics.checksphere for the transforms location from my ai.
There are many ways to get a reference programmatically. Finding by tag should work. If it doesn't, debug it.
It's ubiquitous and used often. The event invoked passes a value to the subscribed delegate(s) . . .
To pass the parameter to the subscribers. It's quite normal, and useful
what if the event is subscribed to a method without an argument? is it just ignored?
The event is not subscribed to a method. A method can be subscribed to an event. And it needs to match the events signature for you to be able to subscribe.
So, if the method doesn't have the correct argument, it can't subscribe to the event.
How do I get the normal of an OnTrigger event?
you can't . . .
only with OnColliderXXX . . .
Is there any mathematical trick or?
what is the normal of an on trigger event even mean?
collisions with contact points have normals
what does it even mean for a trigger to have a normal? you have a shape inside another
A line drawn perpendicular against the closest contact point I guess
there are no contact points
because it is a trigger
fyi, you can have a non-trigger collider that doesn’t send/recieve forces
colliders have force override settings
if you set the layer override to: Send Forces layer mask = 0 (ie nothing), it will send no forces to anything
you can do this both in inspector dropdown menu when looking at a collider, or set it via code
I don't see any such option?
a trigger is just a zone that an object can enter/exit. the only thing you can equate (calculate) from the collision is the direction . . .
when was the feature implemented?
for context I'm using 2021.3.28f1
This is only in 2022+
having that rn would remove so much headache
I'd back up your project, upgrade editor, and see if anything breaks
I fuck with layer overrides a lot
you can turn off certain layer collisions temporarily
the hell is that? 🤨
I have literally never used them haha.
Brand new fanciness haha. On all colliders afaik
they are useful when you want to give something a little bit different collision properties without defining a whole new layer
or when you want to temporarily make something intangible (to force) while still sending collision callbacks
for example, you might want a goomba that walks into another goomba, and it knows to turn around.
you don't want forces to get involved, because goombas actually can pass through each other (and don't usually make a janky stack without a special case)
but you do want the collision callback so they know they touched, to turn around
this is a great tsime to use a layer override, and it's a lot easier/simpler than other method
make sense?
hi, I need some help with ads mediation / iron source sdk.
has anyone encountered this issue where video and interstitial ads just popup up and close on their own without fully playing on an android build?
version info:
- unity version: 2021.3.30f1
- installed ads mediation package through package manager
- used LevelPlay integration manager to:
- update iron sdk to latest version (also had this same problem using the v7.2.x)
- install unity ads adapter
look for errors in logcat. Do you have any dev options enabled on your device? There's one called don't keep activities that can cause problems
(on Android, you didn't specify platform)
i haven't installed the logcat package. will do that and check for errors. thanks for the suggestions! i'm testing on android, will update the original message
update: checked my options, don't keep activities is off
For giggles, have you tried testing it in portrait mode?
Are you forcing the app to landscape?
ahh it was because i have auto rotate off. i just tried turning auto rotate on and the ads play properly. yes i forced the app to landscape and haven't tried portrait mode. didn't notice any errors that looked like it was from playing the ad in logcat too. thanks!
I understand that I'm in the wrong channel for this, but is anyone able to help me with an input system issue, i havent gotten a reply in there for 2 days lol #🖱️┃input-system
Perhaps you guys can help me debug this one. So the issue I have is I was generating my chunks vertically using local Y co-ordinate, which made the chunks disconnected vertically (as in they would look like slices):
float[] blendedNoise = new float[currentBufferSize];
int chunkHeight = GridMetrics.PointsPerChunk(lod);
for (int x = 0; x < chunkHeight; x++)
{
for (int y = 0; y < chunkHeight; y++)
{
for (int z = 0; z < chunkHeight; z++)
{
int index = x * chunkHeight * chunkHeight + y * chunkHeight + z;
float heightFactor = (float)y / (float)chunkHeight;
blendedNoise[index] = BlendNoise(terrainNoise[index], caveNoise[index], heightFactor);
}
}
}```
And after updating the code to use a world Y co-ordinate, I no longer see the vertical chunks.
```csharp
float[] blendedNoise = new float[currentBufferSize];
int chunkHeight = GridMetrics.PointsPerChunk(lod);
float worldHeight = 256.0f;
for (int x = 0; x < chunkHeight; x++)
{
for (int y = 0; y < chunkHeight; y++)
{
for (int z = 0; z < chunkHeight; z++)
{
int index = x * chunkHeight * chunkHeight + y * chunkHeight + z;
float globalY = (globalOffset.y * chunkHeight) + y;
float heightFactor = globalY / worldHeight; // Calculating heightFactor based on global position
blendedNoise[index] = BlendNoise(terrainNoise[index], caveNoise[index], heightFactor);
}
}
}```
This is what I was trying to debug, like why it doesn't work anymore ? I can see the vertical chunks being generated in the object hierarchy, but they are invisible in the scene, this sort of points out to an issue either with the noise generation (may not have Y ?) or with the chunk generation, but not sure.
Before: All the vertical chunks were disconnected, and I think the issue is because I was using local Y co-ordinates for the height factor.
After: I am now using global Y co-ordinates, which "should" solve that issue, but instead I can no longer see the vertical chunks being generated at all.
Note (the slices you see, are not 1 chunk, it's like 9 chunks or so per slice. So the horizontal chunks generate still fine in both scenarios. It's the vertical chunks that I have issues with.
- I have a script that is using an audiosource component. They're both on the same object. When i quit, it triggers a sequence of calls starting from other objects' on destroy, which leads to a method that this script has. In there it refers to an uadiosource component, which appears to be destroyed at that point. Other than doing that wasteful null check which is going to occur only ever once during a session, how can i handle this?
You've said 2 things
A wasteful null check
Itll only ever happen once
Which one of these statements above is true? if it happens once then just write a null check and move on in your project.
If its wasteful then it must be happening extremely often, in which case you should profile it and see that it's not wasteful. Meaning you again should just write the null check and move on
-
By "only happens once" i mean meeting the null check. In all other cases it's guaranteed to return false, and will only trigger during the application quit
-
The thing is not used every frame, but a dozen of times within a single one with large intervals between such "bursts"
-
Ig it's just my perfectionist speaking. I never liked these null checks of unity objects. Thank you regardless
🤷♂️ the issue is that something is unexpectedly null, you need something that conditonally does your logic as long as the object exists. any work around would just be involving an if statement and some bool
can you do dictionary lookup with 3 inputs ?
Nvm that would be an array 😂
But... its gonna be extra big
like 100x100x100 is 1000000
what input? you could do that yes with the key being a vector3 if its floats for example. i dont know what you mean by that would be an array
ohh
Nothing im gonna try to use a dictionary them. I thought i cant and id have to use an array to lookup things but nvm
i didnt realize i can use vector3 as a key in dictionary
I am using an enum with getter/setter. How can I make it show in the inspector?
You can only show a backing field in the inspector. If it's an auto property, you can use [field: SerializeField] attribute.
I actually want to have the enum in the inspector and call a function if the enum value is changed. Looks like I might need to create a custom inspector for that
Ah, you want to call a function when you change the value in the inspector?
Yes, I don't really need the get/set but I thought I could use the setter to do that
Custom inspector is one option. Another one is using OnValidate.
ECB from Gameobjects
Thanks! 👍
something like that maybe? If not, there's probably some other funcs attributes
hi so im refrancing all my instatiated objects like this spawnedPipes = Instantiate(genTube, cylinder.transform.position, cylinder.transform.rotation);
then saying this spawnedPipes.layer = 6;
but its not changing any of them
where have i gone wrong
Hello, I have using the Application.persistanceDataPath to save my data. In the docs said the data will not be delete after an update but it does when I update my app
UtilityState.Instance.SavePath = Application.persistentDataPath + "/" + LessonData.lessonId;
the LessonData.lessonId will be a folder contains some others file
but after an update, the folder "LessonData.lessonId" is being delete
something like this should work. I suspect something is happening between those lines to lose the reference
given that code, it looks like you only keep one reference to a pipe, and it gets overwritten the moment another gets instanced
Did you physically navigate to the folder and confirmed that it's deleted?
how would i fix that then
I have check the path in code, it doesn't exist. The reason I can't check physically because I build for IOS
personally, I would keep a collection of the gameobjects that can change in size. I assume you’re doing something like flappy bird
I would keep a List<GameObject>
when are you changing the layer? right after it is instanced?
i would go:
…
GameObject pipe = Instantiate(………);
pipe.layer =6;
pipeList.Add(pipe); ```
in general, whenever I instantiate something, I always try to log a reference to it in case I need to access it later
Hello, how can I create checkboxes like these?
depends on what you are using to do the UI, but like for IMGUI that is just using
EditorGUILayout.Toggle
Thanks!
How do i tell what my raycast hit
Some overloads of the Raycast function give you a https://docs.unity3d.com/ScriptReference/RaycastHit.html as an out parameter
check the Raycast docs for examples of this
I did that it said argument 5 may not be passed with the out keyword
be very careful with the ordering of your parameters
make sure you are doing it the same way as the docs indicate
you likely have something out of order or in the wrong place
note that argument 5 is NOT where the raycast hit param should be
so it's definitely an issue of the wrong order
Your IDE should give you something like this too to help^
Hey, I have a question about Zenject.
So I have a class
public class Test
{
public Something _Smth;
public Foo _Foo;
private int Id;
public Test(Somethnig smth, Foo foo)
{
_Smth = smth;
_Foo = foo;
}
}
and I install it like this
Container.RegisterNewInstance<Foo>();
Container.RegisterNewInstance<Something>();
then I have a list List<Test> Tests
What I want to do is somehow make a for-loop that will create and add Test to Tests list. I want to make sure that _Smth and _Foo are installed using Zenject and I want to pass Id when I create this object. From my understanding of zenject if i do var test = new Test() it wont work cuz Something and Foo wont be installed right?
How can I do this?
Is there no oneliner to create a list and add one element to it?
var somelist = new List<Part>(part);
this results in error
i want to add part to it
new List<Part>() { part };
I cant figure it out
Where should the out go
Compare what you wrote to the documentation.
Wel theres like 15 overloads and ive only got 3 so idk
overloads just mean there are different combinations of parameters that call different versions of the same function
idk how much help you will find here with zenject, because that seems like a 3rd party addon
i can't find a better place to ask. Zenject is a really popular addon tho so i thought that someone here would be able to help me
pick the one you want to use, and put your parameters in that exact order
again, the docs have code examples
you can make a constructor that just takes the id, then add a separate private method annotated [Inject] that takes the injected values as params and sets them
but from my understanding if I create object like var test = new Test()
Inject wont be called
or am i wrong?
{
RaycastHit hit = new RaycastHit();
pad.GetComponent<BoxCollider>().isTrigger = false;
StartCoroutine("colliderCooldown");
sitCheckFalse();
playerm.isSeated = false;
Destroy(pad);
if(hit.collider.tag == "autumn")
{
Debug.Log("woking");
BroadcastMessage("AutumnConnect");
}``` im getting object refrence is not set to an instance error
Read the full error message, it will say which line is causing the error
yes, part 2 is that you need to call DiContainer.Inject on each instance after constructing it normally (should be able to inject the DiContainer where needed without configuring it yourself i think)
better yet, if you click the error message, it will take you directly to the line causing the error
I have never seen this RegisterNewInstance method in DiContainer, nor can I find anything about it. Is it an extension method you made?
49
ok and which line is 49?
yep
its our extension
oh right haha sorry its the 2nd if statement
Why did you do this? RaycastHit hit = new RaycastHit();
You need to actually use one of the raycast overloads that provides the RaycastHit
this one isn't going to contain any information
you just made a blank one
So when you try to do hit.collider.tag it's an error, since your hit is empty, hit.collider is null
i get the error message hit doesnt exist in current context when i remove it
For the 3rd time, you should really look at the code examples from https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
it will show you how to do this
currently you're just guessing
what is it the querytrigger interaction
3/4 of the code4 examples show how to use the raycast hit
Explained right on the page
Everything you need to know is on that page
you actually don't need to worry about that at all though
look at the code examples
none of them are even using that parameter
it's not relevant
Leak Detected : Persistent allocates 75 individual allocations.
What does this mean? How do I fix it?
well, with no further information, it's very hard to say anything
Have you written any Jobs code?
If you don't know what that means, then the answer is probably no.
Looks like this is happening in the URP renderer
A memory leak occurs when memory is allocated, but never freed (while also not being used anymore)
Short-lived allocations will get marked as leaked if they don't get freed soon enough
But persistent ones are allowed to live for a long time
Does this error appear when you exit Play Mode?
Wdym?
URP has two different renderers.
I believe ShadowCaster2D (which is in your stack trace) is from the 2D renderer.
Oh god I had no idea about this. They've managed to make the render pipeline thing even more confusing 😵💫
i mean, sort of
i find it straightforward enough
the render pipeline is all the machinery; the actual renderer slots into that
By default a 3D URP project will use the standard universal renderer
I believe the 2D renderer was experimental until recently
I need to try it. I've never actaully made a 2D game in Unity...
(i can't draw)
I am using with the 2D Renderer I think
And I am using ShadowCaster2D on some of the GameObjects
What version of Unity are you using, and what verison of the URP package are you using?
(you can find the latter in Window > Package Manager)
render pipeline is pretty confusing ngl. Just a few days ago, I couldn’t figure out why one thing wouldn’t render. Problem: Random checkbox
which was defaulted on, and needed to be off
and normally works fine. Except in 2D, with a certain type of particle, and only when instantiated during runtime
huh?
never had this problem before
well, then you've never tried to do this before
2023.1.9f1, 15.0.6
I think I have?
unless foreach doesn't work with lists of vector3s
what type is pathpoints
List<Vector3>
C# won't let you assign to a foreach iteration variable
You're trying to assign to a foreach iteration variable
Use a for loop
on which line do you assign to effect?
I dont
pos is a struct. the iterator gives it to you
you also can't do something like
You are not assigning a new thing to effect
Pos.x += 1;
same error
Right.
it’s like if pos was 4, and now you are trying 4 += 6. That doesn’t make sense
It's like doing transform.position.x += 1;
well, it's not quite like that
my point is: you don’t have a reference to the vector. you have a vector
at least I think he does
thats so wierd
maybe it just doesn't work with structs
but I can assign to members?
i assume if it is reference type, you could modify the underlying variable, but not assign to it
but not if its a vector3 iterator
You can't assign to a value type member because you can't assign to the variable.
^
2023.1.9f1, 15.0.6
If you want to mutate the contents of the array, write a normal for loop
I have a gameobject (let’s call it A) that is a child of another object (called B). When A is moved around, the parent B stays in place. I want to periodically update B (the parent) to be at the position of the child. When this happens the child moves because it’s local transform is relative to the parent, so I essentially need to reset the child transform to zero it out. When I do this, I encounter a split second where the child A snaps to a new position relative to B, and then snaps back to be at the same spot as B. How do I update B’s position and A’s transform so that it happens seamlessly?
not a code problem. ask in #💻┃unity-talk
or go nuts
Vector3[] foo = new Vector3[3];
ref Vector3 neato = ref foo[2];
neato.x += 3;
2023.1.9f1, 15.0.6
I saw the first time :p
lol
This is the tech stream version of unity, so it's more likely to have bugs than the LTS
It's probably not a big deal.
the LTS does not work properly for me
But I think I installed URP not correctly
I started the project as legacy 2D
and then switched to urp
and from then weird things started to happen
like the memory leaks
I would just cut my losses and ditch the parent child relationship
And just control the transforms manually?
sounds like you're doing it out of order
The update order will be very important here.
How are you currently doing this? Show your !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.
I’m away from my desk atm so I can’t unfortunately 😦 I was messaging here for some ideas as I was thinking about it
Don't cross-post, this is not a programming issue
Logging is very expensive
Unity has to generate a full stack trace and write a bunch of stuff into the console
Stack trace generation can be very expensive at times, the logging itself is cheap in comparison
the error only happened once at the launch of the game
surprised that would drop from 200fps->120fps
If it happened once then the logging of the error itself is unrelated to the ongoing performance issue
Hey, When I click W and D key together or any one key on each axis I get the input magnitude 1.414. Why is that I should be getting 1 only
show your code
because the square root of 2 is 1.414
Debug.Assert is generally more useful, and lighter
Oh my dumb ass, got it!!
at least in deep profile, Debug.Assert normally mostly costs the string.concat for the error messages I generate. Which need to be generated to call the function
oh, that's handy: it logs an error, but doesn't throw an exception like UnityEngine.Assertions.Assert's methods do
Should I place #if UNITY_EDITOR in front of using Unityeditor?
You should if this file is making it into the built game
so if it's outside of an Editor folder, yes
not sure where to ask this - for making levels, say i want to make a maze. so far i'm just scaling up cubes and shoving them in various places. this feels like the very naiive way to do it - is there a better way?
colliders, also make sure you move with rigidbody and not translate
or generate it procedurally
give them colliders and dynamic rigidbodies
(and make sure your player is moving via forces)
procerderal would be interesting, but I know very little about procederal generation
Always a good time to learn
true...
Or velocity
if you are making mazes, you want procedural generation
unless you just want a one off simple maze, like the sacred forest in ocarina of time
InvalidOperationException: Trying to release an object that has already been released to the pool.
UnityEngine.Pool.ObjectPool`1[T].Release (T element) (at <3b24cc7fa9794ed8ab04312c53e6dedd>:0)
Bullet.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/interactable/Bullet.cs:45)
Is there a way to check if an object has already been released before trying to release it?
imo this error shouldnt be happening anyway
but it still annoys me
void OnTriggerEnter2D(Collider2D collision)
{
var tag = collision.transform.tag;
if ((tag == "Fighter" || tag == "Player") && tag != shooterTag)
{
Fighter colFighter = collision.GetComponent<Fighter>();
colFighter.Damage(dmg);
//Debug.Log("Pool Release called");
fired = false;
StopDestroyAfterDelay();
pool.Release(this);
}
else if (tag == "Wall" || tag == "Floor")
{
fired = false;
StopDestroyAfterDelay();
pool.Release(this); **Line45**
}
}
why not make sure fired is truew or someting
before releasing
or add another bool
that could work...curious how it may be doing error rn anyway
once it "releases" it shouldnt be able to have collider interact with anything anymore?
void ReturnBulletToPool(Bullet bullet)
{
//Do Particle Explosion
EffectType effect = EffectPooling.instance.effectPools[bullet.effectType].Get();
effect.transform.position= bullet.transform.position;
bullet.gameObject.SetActive(false);
}
should immediately be SetActive(false) once released
interesting
I tried this and still getting the error...its a lot less
but still occasionally
void OnTriggerEnter2D(Collider2D collision)
{
var tag = collision.transform.tag;
if ((tag == "Fighter" || tag == "Player") && tag != shooterTag && fired)
{
Fighter colFighter = collision.GetComponent<Fighter>();
colFighter.Damage(dmg);
//Debug.Log("Pool Release called");
fired = false;
StopDestroyAfterDelay();
pool.Release(this);
}
else if (tag == "Wall" || tag == "Floor")
{
fired = false;
StopDestroyAfterDelay();
pool.Release(this);
}
}
I would just do
if (fired) return;``` right at the beginning of the function
good idea...tossing
if (!fired)
return
before any of the tag checks or things run fixed it
is it just the other code might be too slow
no
else if (tag == "Wall" || tag == "Floor")
{
fired = false;
StopDestroyAfterDelay();
pool.Release(this);
}```
you had this
which is still potentially releasing it without checking if fired was false already.
How to generate a random string that could work as an ID ?
ah gotcha
Guid.NewGuid().ToString()
still not sure why fired would need to be checked since it should only release
and the disable the object
if OnTriggerEnter2D happens twice in the same physics frame, it can run twice here
this can happen if you have multiple colliders or are overlapping with multiple things simultaneously
ah ok thanks, forgot that it could collide with 2 things same frame 😄
so for having an object "redirect/richochete" when hitting a wall/floor its easy, you just multiply X by -1 for wall, Y for -1 for floor
issue Im having is how do you tell its a floor or wall on something that has a floor and wall side
ex) a square has a side that would be wall and top would be floor
typically you'd just reflect the velocity vector over the surface normal
the code is simpler, and the math will work for any surface orientation
not just straight vertical/horizontal surfaces
that makes sense...I say while googling what a surface normal is and how its found 😄
you can get the normal vector from any Collision callback or from any raycast-like physics query
As for the reflection: https://docs.unity3d.com/ScriptReference/Vector3.Reflect.html
yes exactly
so I would do
Vector3 newmovement= Vector3.Reflect(movement, collision.normal);
yep
assuming my walls aren't bumpy that will work much better thanks 🙂
might have some weird interactions if the walls are bumpy lol
any chance you know a workaround?
or will I have to make it on a collider instead of a trigger
you can still get a normal with a raycast
gotcha thanks
raycasts and I dont get along very well 😄
they're very powerful tool
oh for sure
I just tend to spend a lot of time debugging them whenever I have to use one
yeah gizmos are life saver for that
at least it doesn't take my scripts 20s to save anymore
even with gizmos trying to bug fix like 5x takes a few minutes for a 2s code change
😦
.collider
You need to get a contact point
should I just grab the first one?
collision.GetContact(0).normal - this cannot fail since there's always at least 1 contact point (at index 0) for a collision
_enemy.detectorWallNormal = collision.contacts[0].normal;
That creates an entire array to get the first element, don't
Use GetContact
There's both
GetContacts is useful if you want to get all of them
lol
walks away in shame
bye navarone's messages 😄
Now it looks like I'm talking to myself
lol thought you were using Collider2D because triggers
I was
then I wasn't cause I was told I can't use triggers to get the normal
yea true, what I mentioned you can raycast to the collider to get the normal
its how i fake my bullets sometimes
public class ColliderDetector : MonoBehaviour
{
private EnemyCharacter _enemy;
[SerializeField] string WallTag;
[SerializeField] string Floor;
[SerializeField] string Platform;
Collider2D myCollider;
private void Awake()
{
_enemy = GetComponentInParent<EnemyCharacter>();
myCollider = GetComponent<Collider2D>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag(WallTag))
{
_enemy.detectorWall = true;
_enemy.detectorWallNormal = collision.GetContact(0).normal;
}
else if (collision.gameObject.CompareTag(Floor))
{
_enemy.detectorFloor = true;
_enemy.detectorFloorNormal = collision.GetContact(0).normal;
}
else if (collision.gameObject.CompareTag(Platform))
{
Debug.Log("hit platform");
Physics2D.IgnoreCollision(myCollider, collision.gameObject.GetComponent<Collider2D>(), true);
}
}
why is this not disabling the collision between collider and platform at the end when they hit
The Debug.Log is firing
Collision already happened at the time IgnoreCollision is called
thats fair, however my object will still continue to collider with it after this is called
it might even leave, fly away, come back and collide again
which object has ColliderDetector
the enemy thats moving around
do you only have 1 collider / are you sure ur grabbing the correct collider?
prety sure to both
however I just saw I can have the collider2d itself just ignore the layer in inspector so I'll probably do that instead 😄
I think this should work
same lol
yeah, it's relatively new (in 2D physics)
I didn't want to have to go into physics and mess with adding layers and disabling for everythign
imso used to collision matrix, this looks handy
time to debug..
maybe Print a little more info on what ur actually hitting / layer name n all that stuff at runtime
something must be off
I got it paused
they are showing up in each others contacts
moving to #💻┃unity-talk
If I have a grid, or a 2d array resembling a grid, or a grid in some other form
https://i.imgur.com/0xfJ9nx.png
Anyone knows how to detect the fields/tiles/squares/cells that were hit by a straight line between two positions ?
each grid cell has position and size specified, and the size is the same for every cell
I think is calledhttps://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
or would it be Digital Differential Algorithm? sorry If its not helpful
Bresenham's line algorithm is a line drawing algorithm that determines the points of an n-dimensional raster that should be selected in order to form a close approximation to a straight line between two points. It is commonly used to draw line primitives in a bitmap image (e.g. on a computer screen), as it uses only integer addition, subtraction...
I want to share some functionality between Mono and non-Mono scripts, how do I do it? I can only derive from one class...
create a third helper class
If it's just a bunch of static methods you need, you could even make it a static class
How should I name a class which has methods like these?
protected void UndoCreationIfEditMode(GameObject gameObject) {
#if UNITY_EDITOR
if(!Application.isPlaying) Undo.RegisterCreatedObjectUndo(gameObject, "create scene object");
#endif
}
protected void DestroyInEditOrPlayMode(GameObject gameObject) {
#if UNITY_EDITOR
if(!Application.isPlaying)Undo.DestroyObjectImmediate(gameObject);
else GameObject.Destroy(gameObject);
#else
GameObject.Destroy(gameObject);
#endif
}```
EditorObjectManager or something? Idk
there's also no reason these funcitons can't be static as far as I can tell.
they already take a parameter for the object they are intended to manipulate
I just can't choose a good name
But the second method works without undo too
Look, there's two hard things in progamming:
- Cache Invalidation
- Naming things
A skinned mesh renderer has several materials and I tried changing them by taking them by index but I get an error. How should materials be changed in this case? (I don't get an error when there is only one material and I access it with .material)
typically:
Material[] materials = myRenderer.materials; // OR sharedMaterials
// make any changes you want to the materials array
materials[someIndex] = someMaterial;
// assign the modified array back to the renderer
myRenderer.materials = materials; // OR myRenderer.sharedMaterials =```
(this works for any type of Renderer)
Thanks a lot!
Anything that I change in any object in an IEnumerator method will revert back to default when the method is finished. Anyone know why this is happening?
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.
pastebin for the method
I would like someone helping me cuz i typed my problem in beginner and input system but nobody helped
https://pastebin.com/yG2rutzL
And here's the pastebin for when said method is called
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.
What's an example of a thing that changes back?
Can you also share the rest of the code?
Yeah
https://pastebin.com/wkfRLidt
Full code
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.
and gimme a second to get an example
first log is sent from within the IEnumerator, second is sent right after
where in the code are these log statements exactly?
First one at line 176, second was inserted between line 199 and line 200
gonna be gone for a while, I'll respond to whatever you send when I get back
At first glance it feels like a struct value-type semantics kind of issue
I am trying to change a URP RenderFeature settings through code. I have the RenderFeature referenced and when I do renderFeature.GetComponent<RenderObjects>() I get a NotSupportedException.
Should I reference the RenderObjects directly?
Maybe show the full error
NotSupportedException: Specified method is not supported.
Unity.VisualScripting.ComponentHolderProtocol.GetComponent[T] (UnityEngine.Object uo) (at ./Library/PackageCache/com.unity.visualscripting@1.9.0/Runtime/VisualScripting.Core/Utilities/ComponentHolderProtocol.cs:70)
Chaos.UpdateScreenSpaceEffect () (at Assets/Scripts/Chaos.cs:139)
Chaos.OnValidate () (at Assets/Scripts/Chaos.cs:71)
Hmmm, I am not even using visual scripting at all
What's on line Chaos.cs:139
You might have accidentally imported the wrong type somewhere
I would:
- uninstall Visual Scripting if you're not using it
- double check your
usingdirectives in Chaos.cs
This is in that line ^
RenderObjects ro = renderFeature.GetComponent<RenderObjects>();```
^ do these
I tried referencing it directly and it is working
Apparently render feature doesn't support your specific method call which seems to be get component
we don't know what type renderFeature is though
which is very important
seems like it might be a ComponentHolderProtocol whatever that is
some Visual Scripting thing
doesn't Renderer Feature use ScriptableObjects ? you probably referenced wrong type
It's ok. Referencing it through the inspector works but for some reason it doesn't update on the scene, only in the inspector. Is there some update call that should be done on the UniversalRendererData or ScriptableRendererFeature in order to have them update in game?
whats ur current script?
You'd probably want to define work and doesn't work as well
Your prior stack trace suggests this is an on validate callback which wouldn't change unless the inspector value changes
renderObjects.settings.overrideMaterial = someMaterial;
The material is being changed in the inspector on the RenderFeature, however it is not being changed in the scene. When I do the same thing manually, through the inspector, it does get updated in the scene.
(RenderObjects is a built-in RendererFeature in URP)
it would help if you sent at least the full script so we get an idea where everything is called
I will write the relevant parts as the script has lots of stuff in it.
[SerializeField] private ScriptableRendererFeature SSTextureFeature;
[SerializeField] private RenderObjects renderObjects;
[SerializeField] private List<Material> screenSpaceMaterials;
private void OnValidate(){
if(/*a certain enum value has changed*/){
UpdateScreenSpaceEffect();
}
}
private void UpdateScreenSpaceEffect()
{
//currentScreenSpaceEffect holds the current value of the enum mentioned above
if(currentScreenSpaceEffect == ScreenSpaceEffect.None)
{
SSTextureFeature.SetActive(false);
return;
}
SSTextureFeature.SetActive(true);
//line 140
renderObjects.settings.overrideMaterial = screenSpaceEffectMaterials[((int)currentScreenSpaceEffect) - 1];
}
But I don't think it really matters as it does do what it is supposed to do and when it is supposed to do it, the issue is in the fact that the scene is not updating with the new settings.
It only updates with activating/deactivating the render feature but not with updating the material
i might be wrong but try acessing renderer component instead of material and then get to material from there
Got it. I just need to set the ScriptableRendererData as dirty
Switched it to a class instead of a struct and that worked, thanks!
It finds most of them but not all. It seems instead of choosing all the cubes it passes through, it ignores the cube where the intersecton was smaller
void Draw3DGridLine()
{
Vector3 start = origin.position * 10f;
Vector3 end = target.position * 10f;
Vector3 delta = end - start;
int steps = Mathf.Max(Mathf.RoundToInt(Mathf.Max(Mathf.Abs(delta.x), Mathf.Max(Mathf.Abs(delta.y), Mathf.Abs(delta.z)))), 1);
Vector3 step = delta / steps;
List<Vector3> points = new List<Vector3>();
for (int i = 0; i <= steps; i++)
{
Vector3 point = start + i * step;
points.Add(point);
}
}
Anyone knows?
yeah that algorithm does that on purpose afaik
kinda shown in this image
I am casting a ray down to the floor to check what type of layer the floor has however the out hit returns null each time. SUper confused. The layer is set up and I can see the ray being cast and passing through the floor
which line of code is currently running here?
It passsed the if statement
Looks like you're inspecting hit before the raycast ran
right if the raycast function returned false that means the raycast didn't hit anything
so hit will not be populated
There is no point for this
I get that, but it should be hitting somethig
hit.collider will NEVER be null. The raycast can only hit objects with colliders
well it's not. Time to check why
perhaps your raycast is in the wrong place, or the object you expect to hit has no collider
or the collider isn't where you think it is
Debug.DrawRay is a common tool to debug raycasts
Well, The collider is a mesh collider . It's the floor. The ray passes through the floor
The debug.draw is in the images I sent
you can see the line
that image is hard to parse visually
unclear if the raycast is starting above the floor or not
or if it's ending below the floor
it could be entirely above or below the ground
I starts aboce the floor ends below
there's no perspective
ok and, show the floor's inspector?
Show where the collider is?
and what layer it's on
etc
also show the Debug.DrawLine or DrawRay call that drew this
LAN connection.
If I start server on phone and connect from computer trough phone IP, I can connect.
But if I run server on computer and try to connect by phone with the computer IP, I can't connect.
That would mean my computer is blocking incoming connection request, right?
yo can somebody help me? i dont see my handlebuttonclick in the function dropdown for the ui button, heres my code
!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.
your function is private
it must be public if you want it to show up
oh wait
im dumb
thank you
Henlo, Cloud code C# modules, cloud save data. I want to access 2 player's data via my game server, how would I do this?
What are you using for the cloud save data?
Floor save data?
public DockScript dS; im making a variable for another script here to access a bool but when i use this if statement if (hit.collider.tag == "Autumn" && dS.autumnIslandConnected == false) im getting the object refrence not set to instance error```
Where and how do you reference dS
And I'm assuming it's not hit, because this if statement is in a raycast if statement, right?
yeah it was working fine before but as soon as i added dS.autumnIslandConnected it fell to bits
Ok, then the error is for dS
Where and how do you reference dS
only in them two places
How do you ASSIGN the reference I mean, sorry
Sorry. I meant to say "cloud". The damn autocorrect...
public DockScript dS; there
That is declaring the reference, not assigning it
omg i forgot to drag it in ima kms ffs XD
Ahhhhh, that'd do it
cheers
the first step to fixing your game is acknowledging you will never succeed
once you accept this, the second step is giving up.
and bam: you don’t have to handle updating anymore
var apiResponse = await gameApiClient.CloudSaveData.GetItemsAsync(
context,
context.AccessToken,
context.ProjectId,
playerId,
new List<string> { PlayerInventory.Keys.MatchDeck }
);``` on my C# module. gameApiClient is `IGameApiClient` sourced by `GameApiClient.Create()`. `playerId` is a string, the other player's Id
As it stands, the requesting user (currently anon login) does not have perms to check the other player's (also anon) data. I don't know if it is possible to make the request as an admin of some sort.
The C# module is called via Unity's CloudCodeService.Instance
how tf do i fix this 😭 :
Show the code. Looks like you used a string when you should have used an enum?
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.VR;
using Photon.VR.Cosmetics;
public class ChangeLeftCosmetic : MonoBehaviour
{
public string Left;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("HandTag"))
{
PhotonVRManager.SetCosmetic(CosmeticType.LeftHand, Left);
}
}
}`
(this code isnt mine, it's from this repository on github. https://github.com/fchb1239/PhotonVR)
Ah, it is SUPPOSED to be a string I guess? I read the error wrong. Lemme take a look at the link
Hello! Quick question: Is it bad practice to move a kinematic rigid body inside of update?
I see this in that repo
PhotonVRManager.SetCosmetics(new Dictionary<string, string>
{
{ "Head", "VRTopHat" },
{ "Face", "VRSunglasses" }
// And so on
});
Sorry, I've no experience with CloudCodeServive, so can't help you there.
It wants a dictionary with strings as the key and value I guess?
Ah, or this
PhotonVRManager.SetCosmetic("Head", "VRTopHat");
It's usually taken care of by the publishing platform. Steam would try to update the game automatically if you uploaded a new build for example.
If you don't use any publishing platform, you'll need to implement some kind of launcher that does it for you.
the "VRTopHat" and "VRSunglasses" are both example 3d models that don't exist in my project.
so maybe that's the problem?
im a dumbass soooo lol
I think the issue is that you need to just use strings? You wrote Left but you need to write "Left"
I dunno how that string translates into getting the asset, but it probably needs to be referenced somewhere as that 🤷♂️
It just needs to be a string though
alr i gotchu
nope 😭
It looks like the string uses the gameobject name:
"Every body part on the player has a child named something with "Cosmetics", under those you put the models of the cosmetics you want. You have to rename the object to the ID of the cosmetic, let's say you put on a hat with the ID "VRTopHat" then under the Cosmetics child of the head you put your model and name it "VRTopHat", like this:"
Theres a picture at the bottom of the repo you linked
Do you HAVE an object named "Left"? Is it a child of an object called "Cosmetics"?
I cry. I guess I'll ask in advanced
Left was already a string
Show your current code.
In here?
#archived-code-general message
Ahhhh
yes, Left is a field
Yep, I see it
did you do uh
The other one was enum though
public string "Left"
Right? Lol
Every instance of the method I can find takes two strings
so, yes, CosmeticType is not a valid argument there
the method takes two strings
give it two strings
hence the error complaining you can't convert from Photon.VR.Cosmetics.CosmeticType to string
because the method wanted a string and you gave it a Photon.VR.Cosmetics.CosmeticType
This is invalid syntax.
I've been trying to understand how picking a random item from a list of weighted values work, because i think it'd be the best option for picking rooms in a dungeon generation algorithm.
If i have say, 3 items, call them A, B, C. and all of these items have a weighte value of 10.
I assume then each item has a... 33.3% chance of being picked?
sum up the weights, then pick a random number between 0 and the sum
iterate over the list, subtracting each item's weight from the random number as you go
if the number reaches zero, return the item whose weight you just subtracted
hmmm...
ok lemme see if i can implement this right
cuz i've been working on a custom collection for this kind of stuff
float startWeight = _rng.RangeFloat(0, TotalWeight);
for(int i = 0; i < _items.Count; i++)
{
startWeight -= _items[i].weight;
if (startWeight <= 0)
return i;
}```
methinks this should work then.
heck
i mean, that didnt really answer my question regarding the probability
because currently only one item is being picked constantly
i assume its because all three items have the same weight?

each item should have an equal chance of being drawn
how are you creating that _rng object?
rng is a custom Random number algorithm i found on github, cant recall where
why are you using a custom pseudorandom number generator
Xoroshiro128Plus i think is the algorithm it used?
its seeded
mainly because of that
so is every other PRNG
Unity's global
System.Random can be constructed with a seed
You can also save and restore the state of UnityEngine.Random at will
by accessing Random.state
Show your code. If you're not getting random results, I suspect you're deterministically seeding your RNG
you can sanity check your RNG by logging a random integer
will do
I was doing that two days ago while tracking down an rng bug
https://gyazo.com/17421279c905bfd44f7b2a81a2eb48dc
NextInt does seemm to be quite random, regardless, lemme hastebin the code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Aight. I just need this: How do I authenticate as a service account via some Unity library?
I'm looking for your code, not the RNG's
my bad
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
worth mentioning that the seed i use for the WeightedCollection on my current attempt is basically taken from another instance of my RNG, which itself the seed is set to the current DateTime.Now.Ticks
converted to ulong
i would suggest just using Random.Range to rule out a problem with your RNG
I see that you're logging startWeight already, though
if you have three items of weight 10, then you should see a total of 30
with random values between 0 and 30
here's how I did this, by the way
yeah, 50 + 50 + 50, 150
so thats correct
lemme checkout something

well
the first line is just the start weight, and its always the same value
so... ugh
ok lemme see if removing that custom rng andd replacing it with System.Random works
yeah my RNG is just fucked
guess i'll just use System.Random
and subclass it if need be
Hello, why my Ah, nothing. It's because I set translation to 0v and p matrix are not zero but the inverse matrix of their multiplication are?
letting you know (because i belive i should always say what my outcome was for future people's sake), turns out the custom rng class i have is fine, i just used a constructor that basically creates a copy with the same rng states
so... yeah, of course the same outcome was happening when all of them where on the same state instead of different ones
indeeed
that's the one i was using
now i'm just using the already existing rng class and generating a new seed from it, instead of using the copy constructor
I started a new project a week ago. I was able to build and run it without issues. But now, I Build and Run, it goes into script compilation, and shortly stops building, doens't output any logs at all. No build completed, or failed logs, nothing. Just stops. Doesn't write anything to the build folder either. I tried "Clean build", same thing. Anyone else had these issues? Why would it silently stop and not say anything.
screenshot console window
build and run then screen it?
ye
woah! it worked Now it shows errors, that's weird. Let me address those first and hopefully that will do it.
I'm having a weird desync with connecting NavMesh to root-motion movement. If I plug the desired velocity parameter from the agent and convert it to local space into my animator paraneters, the agent starts acting weird. It doesn't path around objects, sometimes it moves away from its target, it may walk out of the NavMesh, or it simply stops as if it reached its destination. I've also tried getting the vector from nextPosition to the agent's position, normalizing it, applying my speed multiplier, and then plugging those values into my animator paraneters, it doesn't desync but the model vibrates due to nextPosition being enlarged so much after being so small. Has anyone done something like this able to help me?
wdym convert it to local space into animator parameters?
I have two parameters in my animator, x and z, that control the blend of the animations. The navMesh coords are in world, so I have to convert it to local. Local vs world isn't the problem, I've tested them both.
hmm is there a reason you're not using agent velocity instead of doing coordinates?
I did use velocity, it's in world coords.
can you show script?
Yeah, give me a sec though.
{
//Only redo the path sometimes (every 1/15 of a second default)
if (updateClock <= 0)
{
agent.SetDestination(target);
updateClock = 1 / navMeshFrames;
}
else
{
updateClock -= Time.deltaTime;
}
//Get the vector from the nextPosition property.
//Doesn't work.
/*
Vector3 worldMovement = agent.nextPosition - owner.transform.position;
worldMovement = worldMovement.normalized * speed;
Vector3 localMovement = owner.transform.InverseTransformDirection(worldMovement);
*/
//Smoothes the movement. Doesn't work either.
//Code from https://docs.unity3d.com/2021.1/Documentation/Manual/nav-CouplingAnimationAndNavigation.html
/*
float smooth = Mathf.Min(1.0f, Time.deltaTime / 0.15f);
smoothMovement = Vector3.Lerp(smoothMovement, localMovement, smooth);
*/
//This doesn't work.
agent.speed = speed; //Doesn't do anything for now since speed isn't changing.
Vector3 localMovement = transform.InverseTransformDirection(agent.desiredVelocity);
animator.SetFloat("MovementX", localMovement.x);
animator.SetFloat("MovementZ", localMovement.z);
}```
does any one know what endless runners use to make the map infinate and can refer a bideo to me
Type "unity endless runner" into youtube and you'll have at least 3 different series covering that
Hello guys I have a game that consists of a main game and a few mini games that are triggered from it in the same scene. Currently my games are badly coupled and require a lot of editor references. I want my mini games to basically be "plug and play". If I add a new one into the future I want it to be easy. Can you recommend a design pattern that I can look into and implement to solve this problem?
https://hastebin.com/share/ocoqiyetiw.csharp
in my above script, i'm wondering if there is a better way to handle this part
private void Update()
{
if (spinDuration > 0)
{
spinDuration -= Time.deltaTime;
Spin();
}
else
{
UpdateLayout();
}
}
where its not always calling UpdateLayout every frame.. that's bad for performance right?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
That looks like it wouldn't really hurt performance to me, unless there are a lot of children in the parent. But you can test this with the profiler.
i have 5 reels with this script on with 12 symbols each .. my worry is that is that i'm building for mobile webgl and i'm trying to avoid unnecessary method calls like that if i can
To me it seemed like updateLayout only needs to be called whenever the children in the parent become inactive or change size, so unless that happens every frame I believe you could only call upsateLayout whenever one of the children changes in an important way
this seems to work
private void Update()
{
if (spinDuration > 0)
{
spinDuration -= Time.deltaTime;
Spin();
layoutUpdated = false;
}
else if (!layoutUpdated)
{
Debug.Log("layout updated");
UpdateLayout();
layoutUpdated = true;
}
}
its my (probably bad) attempt to align slot reels back to even positions because when they stop based on their "spin duration" it ends up like
so just needed that UpdateLayout called once after its done spinning
i dont know how to use the profiler yet ... i should probably youtube that 😅
Then try to align them correctly or call the function once one is done spinning
Hey all, I am instantiating an object at a target destination. Once instantiated, I am attempting to animate its position on the Y axis, however, it seems as though the animator is resetting the object's x and z positions also. How can I stop the animator from overriding the x and z positions?
Remove the x and z properties from the animation clip. Though I'm not sure if that's possible.
It's not
If you only need to animate the visuals, have a separate object with the visuals animated.
Game logic should be separated from visuals.
Yep, that fixed it, thank you
There is an ECS/DOTS channel here: #1064581837055348857
Ok
ugh trying to set up pathfinding in a procedural world will be the death of me I swear
What is the issue?
I just don't know how to do it thats all
Use the navmeshcomponents package and bake the NavMeshSurface(s) from a script after your world is generated
Assuming it is 3D
the problem is it keeps being generated
its infinite
I've tried having a surface on each chunk but then enemies can't cross chunks
Not sure why it would generate infinitely 🤔
It generates when you call the bake function
no the world does
it just has like 12 chunks around the player loaded at any given time
so I would need to bake again and again I would think
I had gotten it to work somewhat but it caused freezes every time it baked
which isn't good
before I had gotten it to work without freezing but then enemies couldnt cross chunks
Ah I see. Didnt come across that issue since I gen my world on start
Generating them asynchronously would be good but I dont think that is possible at runtime
@static matrix This might work if you put a pre-existing mavmesh surface on the chunk prefab 👀
https://docs.unity3d.com/ScriptReference/AI.NavMeshBuilder.UpdateNavMeshDataAsync.html
I have tried this, it did give me a good result
however, the enemies couldn't move between meshes, and were confined to their chunk
So that is the real issue
Not sure, maybe you need to generate navmesh links between them
yes
I was trying to find a workaround
yeah I've tried a couple things with that
most of my solutions cause enems to kinda glitch when they go between chunks
they keep functioning (sometimes) but it looks bad and can cause them to go thru walls
my other idea was having a link in front of the enems at all times but that also didn't work
All I can think of right now is using a single large navmesh that you update when chunks are created. Maybe limit the area though
I'll tell you if I find some solutoon, I might need to solve it myself too
yeah I couldn't figure out how to do that when async
that got the pathing working totally but caused a freezeframe every time a chunk spawned, which ofc I can't have
I've tried doing custom pathing scripts or having enems that don't really need pathing but those don't work for everything
thanks
I've tried using Application.targetFrameRate because I wanted to see how my game behaves at low framerates. Everything behaves well until I set the target framerate value to something lower than 60. If the framerate is below this value, the game starts to look jittery and rigid bodies become unstable both when moving and when colliding with other objects. All these changes have been observed while running the game inside the editor. I did not create a build of the game in order to see how the "final product" behaves. Is it normal for the game to behave this way when running at under 60fps?
Sounds to me like you are moving rigidbodies in Update (as opposed to FixedUpdate)
And/or abusing deltaTime
If you do things correctly, the framerate shouldnt affect physics, except when the physics loop struggles and reaches the max time step
Rb jitter can be caused by a few things so you should show some code, how you move things etc. And it could be a camera issue too
For example using AddForce with deltaTime
Is there an event raised when a NavMeshAgent collides with another one?
The scene includes a character that is controlled by the player. The character has a CharacterController component. There are also "interactable" objects such as boxes and barrels that have rigid bodies but I never add forces to them. The Rigidbody components are only there so the boxes will behave appropriately when they fall of something. Lastly, there are doors and elevators that have kinematic rigidbody components. Let's focus on the elevator for a moment. If a box is placed on that elevator, it goes up and down with the elevator as you would expect but if the framerate is under 60, the box starts jumping as the elevator goes up as if the colliders are going through each other. I tried moving the elevator both by using Transform.position as well as Rigidbody.MovePosition() and the behaviour remains the same at under 60fps.
Probably need a rigidbody with all the constraints checked and use OnCollisionEnter
This is the main drawback of a CharacterController based character. If you need external physics objects to act on the character, it's going to suck
When a NavMeshAgent collides with another NavMeshAgent it doesn't produce a OnCollisionEnter AFAIK, after all, they aren't colliders
So I guess it may be another method, but don't know which one
I never said NavMeshAgent
(You didn't specify to add Colliders so I thought you mean Rigidbody + NavMeshAgent)
The rigidbody might not behave correctly if the NavMeshAgent is directly moving the object around
Although, from my experience, it's fine
Never had major problems with constraints on, but don't quote me on it
its how I make my agents push physics doors too
I prob should, but I didn't want to deal with the whole collision matrix not detected between certain types
dynamic has more choices
The character controller can wait. :)))
For now, I would like to understand why the elevator and the boxes start acting weird when the framerate drops below 60. They both have rigidbody components(kinematic for the elevator / non-kinematic for the boxes). I tried moving the elevator in FixedUpdate() using Rigidbody.MovePosition() and in Update() using Transform.position and the behaviour still occurs.
Might not be the issue but try enabling interpolation on the rigidbodies and see if it helps at all
A video of the issue could help.
Forgot to mention it. I did that from the start.
FixedUpdate with MovePosition should give good results
Alright, I'll be back with a video in a few minutes. 😄
Then again, I have seen plenty of games that have a similiar issue with elevators lol
You're right! That's why I'm not sure what did I do wrong.
Showing the code and a video would help
Just because you're using FixedUpdate doesn't mean you're doing things in the right order at the right time
I have an issue with my character controller which I don't know how to fix. If I stand still, the jumping animation plays normally, from start to end. However if I am walking and try to jump or running and try to jump, the jumping animation plays 2 times in a row but before the first time even finishes, like only a few frames then it stops.
Normally when waking or running, the jumping animation should only play once, from start to finish, just like it does when I am idling. I have checked my animator settings and they are set up correctly I think, also checked the animation transitions and they look normal, so the issue has to be with the code.
If someone can have a look and tell me how to fix it I'd appreciate, code is here: https://pastebin.com/0qtWKP0j
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.
we would need to see your animator controller
you probably want to use a trigger for the jump animation rather than a bool
You must be going from Walking to Jumping to some other state and back to Jumping again
also you could kill some mess by using blend tree for idle/run/walk
using float for speed control
Here is what happens.
And I only press spacebar once, as you can see it's jumping two times but only when walking or running.
And the jumping animation stops prematurely as well when walking or running.
does your Jumping state have an exit time on its exit transitions
No
Is the jumping state a trigger?
all bools
are the blend times different between the different transitions that enter the Jumping state?
It seems like it's spending a long time blending between Running and Jumping
It could also be that the jumping animation is looping.
Here is all my blends.
you have two bools together probably
oh you have no exit time for Jump, how do you set it back to false?
This is wrong. You should only exit the "Jumping" state when isJumping is false.
isWalking and isRunning remain true even when you're jumping
I typically have a state for IsGrounded where my player is mid-air if not grounded
So it's rapidly transitioning back and forth.
Keep your animator in the Jumping state until isJumping is false
isIdling gets set to false when isJumping is true
That's why that worked fine.
How do I do that exactly ?
add another condition
you can have many conditions
they must all be true for the transition to occur
mp4
That solved it for both!
i'll ffmpeg that one for you
One sec
this is a long one
Thank you very much for the help friends!
3 minutes and 24 seconds is a very long recording, lol
lol
I tried presenting everything. The behavior when the game runs, the code, the way things change when the framerate is below 60.
You can also see the components of the box and the elevator.
so you're talking about the box freaking out
Yes
Description
@hexed pecan, @leaden ice, I'm back with the video presenting the problem I'm facing. :)))
Any help would be highly appreciated.
Uh... anyone?
where is the script?
looking at video for script is tedious
On my phone right now and I can barely see anything in the video since you use nearly black materials 😅
One sec
Yeah the vid is too long, better share the inspectors as screenshots and the code as a paste link. And record the relevant parts on video only
Maybe make a thread too
And lighter material colors
Here you go!
https://pastebin.com/P0ZFxszs
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.
MovePosition this doesn't respect physics btw
I looked through some forums in the meantime and discovered that If I want the coroutine to behave as it is was code running inside of FixedUpdate(), I should use WaitForFixedUpdate() instead of WaitForSeconds(Time.fixedDeltaTime).
I made the change and now the box has the desired behavior when on the elevator.
Please explain.
its very simple really , you're forcing transforms instead of use physics to simulate movement
the result will always be choppy/inaccurate collisions
that'd be Vector3.MoveTowards
i wish you could use the static methods like instance methods
foo.MoveTowards(bar, 1);
yeah apparently my brain this morning, thought MovePosition & MoveTowards were the same 👨🦯
hmm maybe the positions are off
For a second you made me think that I never understoon how MovePosition() works. :)))
lol na myb
I usually don't use kinematic, that threw me off 😅
my boxes are usually physics and use .velocity to keep it close to player cam
How does this InteractiveMove function work?
As you can see, the method that moves the elevator is a coroutine. When the player activates the elevator, the coroutine starts. I don't want the player to be able to activate the elevator again until the coroutine that is already running has finished its job.
The InteractiveMove method simply checks if a coroutine is already active in order to prevent the player from starting another one.
Next time show the code to begin with. I saw IEnumerator and my immediate thought was 'they probably arent using WaitForFixedUpdate'
I don't think this check will work properly
That was indeed the problem. :)))
unless you are doing coroutineActive = null; at the end of the coroutine
Yeah, coroutine reference will not nullify itself when it finishes
I know.
InteractiveMove is called inside of the Interact method which makes a coroutine null in case the criteria are met.
Look
But you are right, @hexed pecan, I was using WaitForSecond(Time.fixedDeltaTime) when I should've been using WaitForFixedUpdate().
This is how things work after implementing the changes.
nice
I still have some work to do with the way the box behaves when it's carried around in order to make it look better but I'll figure something out.
Thanks, guys!
oof yeah that'll do it
any idea what this means:
No UI template found for Ads Service GettingStarted.
looks like it's trying to show you a getting started page for the ads service package and it failed to for some reason
I looked in AdsManager.cs and it´s the type of a function arg
private void HandleShowResultUnity(ShowResult result)
just not declared anywhere
We are saving many objects to JSON but we want to have a little bit of composition. So that we can have several JSON configurable MonoBehaviours on one GO and only some of them on another. What would be the best way to do it? The problem is that I don't know of a way to make it all composable without putting one JSON inside another one which will inevitably lead to problems
Hii, can someone help me with an issue in Unity? I need to control the variable 'y' from the script 'x' (the script 'x' is inside a prefab). Please help me
Provide more details. This is pretty vague
Are you instantiating a prefab and then you want to change a variable on the newly instantiated copy's script?
very simple:
[SerializeField]
PipesMovement pipePrefab; // assign to the prefab
[SerializeField]
PipesController pipesController; // assign to the pipe controller in the scene
void SpawnPipe() {
PipesMovement newPipe = Instantiate(pipePrefab);
newPipe.pipesController = this.pipesController;
}```
(sorry misread pipe as player. Fixed now)
thats from the playerMovement script, right?
Doubt it?
it's from whatever script is spawning the pipes
yes I've just told you how to do it
you are already accessing the speed variable in your script
that speed var is on the pipesController script and i want to acces to it all time on the pipesMovement script
I understood this complete.y My code example will let you do what you want.
yeah, the problem is that i cant assign it on the inspector
I know that
My code will do what you want
it assigns it from the script
oh, let me try
wait if the pipe controller is the thing spawning the pipes you can make this even simpler
[SerializeField]
PipesMovement pipePrefab; // assign to the prefab
void SpawnPipe() {
PipesMovement newPipe = Instantiate(pipePrefab);
newPipe.pipesController = this;
}```
this should be code beginner
object in scene cant reference any components in asset or vice verse
it doesnt work...
it still the same
why did you change the pipe movement script
I didn't tell you to make any changes there
you don't need any changes there
put it back how it was
^ you just need this in the PipesController
put it back like this
^
you dont need to create another field of PlpeController to store the instance itself, you use this to reference itself
ok did... you make the change to the function that spawns the pipe?
and did you assign the prefab in the inspector yet?
just.. do all the things I said to do, and it will work
like that, right?
save it - and make sure you assign the prefab in the inspector
done...
i can delete that, right?
Is there anything besides AudioSource.Pause() and AudioSource.Stop() that can possibly set AudioSource.IsPlaying to false and AudioSource.time to 0?
delete what
waiting for the audio source to finish playing
no there's nothing here you can delete
so that needs to be empty?
yes leave it empty
it doesn't matter
you can even put [NonSerialized] on it if you want
Well, that's just the thing. I'm having the most baffling bug. Midway through a yield return new WaitUntil , a 4 second clip is suddenly being set to IsPlaying = false and time to 0, resulting in the wait ending like halfway through.
show the code?
Visual Studio skips over specific chars, like brackets when you type something. Is it possible to also enable it for '>' and '<' chars?
public void PlayAudioClip(AudioClip clip, AudioConfigurationSO settings, bool hasToLoop, Transform sourceTransform = default)
{
if (!clip)
{
DebugTools.Print("No clip to play: make sure that the AudioCue's clips' audio files are not missing and make sure they were checked out in Plastic if they were set to private", "red", "[sfx]");
NotifyBeingDone();
}
// Stop(); // Stop any existing audio
_audioSource.clip = clip;
settings.ApplyTo(_audioSource);
_sourceTransform = sourceTransform; // Store the source transform
_audioSource.loop = hasToLoop;
_audioSource.time = 0f; //Reset in case this AudioSource is being reused for a short SFX after being used for a long music track
gameObject.name = clip.name;
_audioSource.Play();
if (!hasToLoop)
{
// Stop any existing coroutine
if (_currentCoroutine != null)
{
StopCoroutine(_currentCoroutine);
}
// Start the new coroutine and store its reference
_currentCoroutine = StartCoroutine(FinishedPlaying(clip));
}
}```
{
// yield return new WaitForSeconds(clip.length);
yield return new WaitUntil(() =>
{
Debug.Log("<color=green>" + gameObject.name + " " + _audioSource.clip.name + " _audioSource.time = " + _audioSource.time + " isPlaying: " + _audioSource.isPlaying + "</color>");
return !_audioSource.isPlaying;
});
NotifyBeingDone();
}```
Basically, this is used to play clips for a sound emitter pool (they each contain an _audioSource).
Sorry for all the debug statements.
ohhhh it works, thank you so muchh... Lol now im going to look for how it works
it's not complicated.
newPipe.pipesController = this; sets that empty field
what?
= is used to assign values to variables in C#
It means... this!
Because we're in the PipesController script, it means the PipesController
The one on which the code is running
it's like "me"
this exists inside of any non-static method
because non-static methods, by definition, must be called on a specific object
and that object is this!
ohhh, much clear... and wich is the difference betwen [serializefield] and make the data type public?
both of them serialize the field.
public fields can also be read and modified from other scripts in addition to being serialized
serialization is just how data is copied around in Unity for the inspector and with Instantiate, etc.
public and private are access modifiers. They determine who is allowed to see that member.
public means that any type can access the member. private means that only the declaring type can access it.
Unity automatically serializes public fields. You can use [SerializeField] to indicate that a field should be serialized (e.g. if it's private).
(a "member" is anything inside of a class or struct: fields, methods, properties, etc)
so, in a few words, its the same?
They are not the same. They both happen to serialize the field.
A private field cannot be accessed by any other class.
thank you so much @heady iris @leaden ice 🙂
I have a kinematic rigid body platform which moves using MovePosition. I have a dynamic rigidbody player that I want to parent to it, so player moves in the platform's reference frame.
I can make them move together if I use Translate or transform.position instead of MovePosition, but that doesn't seem right, because that would screw with other collisions, right?
I have tried fixed joint2D and some other joints to try to connect them, but the joints I tried that do make the two things move together ALSO block the player's movement (which is done by forces). Any advice?
there's really no simple way to move a rigidbody in another moving body's reference frame