#archived-code-general
1 messages ยท Page 199 of 1
if this is like a long sequence where you're on a moving platform, you might want to consider moving the rest of the world around the platform instead
I think part of it is that I don't understand the difference between moveposition and changing transform position
I thought moveposition would just allow me to move my rigidbody without interfering with physics calculations.
but for my kinematic rigidbody, its path between points A and B should be locked in. it knows it's going from A to B, and no forces are going to stop it unless it is told to go somewhere else
MovePosition is basically a way to teleport a kinematic rigidbody but realistically push dynamic bodies out of its way in the process
that sounds very important for what I need then. To not change from MovePosition
the important part about MovePosition is that the rigidbody isn't getting moved by someone else
it is response for changing the object's position
so if your player is dynamic, it will indeed be pused by the platform
but "move in its reference frame" is a very different question
because my platform can be a solid block that also pushes dynamic rigidbodies from the side
but I want my player to (if they land on the platform) to move along with it
and my player's physics revolve around no friction
I want this to kind of work like mario, where you can have a bunch of goombas walking on different lifts or whatever, and they are all moving along with their lifts
a fixed joint brings me almost to what I want. player can be on platform, and if he hits a wall while on platform, the wall will take priority and push him.
I just don't know what I need to do to achieve this, as it isn't realistic for me to make multiple physics scenes for this
So what are you currently doing, and in what way is it malfunctioning?
In fixedupdate, platform kinematic rigidbody.MovePosition(nextPosition).
If player (dynamic rigidbody) is making contact and is on top of platform, I want player to move with platform.
I am trying to set playertransform.SetParent(platform), but then player does not move with platform.
if I use platform.transform.position = new position, it would work, but it sounds like the platform would not accurately push other dynamic rigidbodies around
the transform hierarchy has no effet on rigidbody motion
Perhaps the platform can advertise its velocity, and then the player can add that velocity to its own MovePosition call
If the player is moving via normal rigidbody dynamic physics, then presumably the friction from the platform will just drag the player along
and you shouldn't need anything special
maybe a custom physicmaterial to customize the friction level
You can test this - just drop a plain rigidbody cube on the moving platform
it should move along with it just fine
I think this comes down to how your player movement script works
My player has no friction when moving, and the movement is centered around physics. any change to friction would cause player movement to be different between platform and lift
My player has no friction when moving
Well yeah this will be a problem
In real life, friction is the thing that keeps you on a moving surface
This would still work, even with no friction.
I'm going to try fen's idea first, since it sounds promising.
It might misbehave if the platform is moving up or down
it might chuck you into the air
but you could always limit it to only apply the velocity that's tangential to the surface
so, Vector3.ProjectOnPlane(vel, platformNormal);
I'm not sure when Rigidbody.velocity actually updates, so you might want to have the platform just explicitly tell you how fast it's moving
OnConnectToPlatform: playerRb.velocity += platformRB.velocity;
While connected: playervelocity += (platform velocity) - (last frame platform velocity)
When disconnected subtract
(and if it's kinematic, it probably won't even have a velocity at all)
oh right, my first idea would've turned it into a railgun
adding velocity every frame lol
I would need to separately program it to have a velociy in the first place
yeah, that sounds reasonable
I think this is doable, but more complex than all the tutorials which just change transform and parent it
since I'm doing a delta, I probably just need to log transform.position, maybe
this just feels like a super common issue, and struggling with it seems strange
it is a very common concept, yes
because it is so common
although your zero-friction situation is different
as Praetor said, moving platforms don't work with no friction
they just leave you behind
If the platform isn't constantly changing velocity, it'll be relatively easy to get this right
in real world. but most tutorials don't use friction
they do implicitly, though
if you're using a rigidbody, then you have friction
the tutorials do not rely on friction to work, is what I mean
Does a NavMeshAgent's obstacle avoidance not take into account layer-based collision settings? I've set my agents to not collide with their own layer but they're still stopping on each other. Is there a way I can exclude other agents from obstacle avoidance?
I don't think they care about physics layers.
Agents can ignore agents with a lower priority level, but I don't think you can get mutual ignorance that way
Hm, I might be able to make it so there's a hierarchy of them that each ignore the one in front, since they're supposed to form a sort of "conga line" anyway
Problem I'm having is if the front one suddenly turns around they all walk directly into his face and all get stuck on each other
Q: Does MovePosition work properly on dynamic rigidbodies?
Hey, I have a question. I have to save data in my game. I need to save the created levels, the downloaded levels. Is it very good to use SqLite?
You could use pretty much anything, although sqlite would probably require more setup compared to something like json or binary
Thanks for you answer! I think SqLite is good compared to have lots of binary files to store each levels is it right?
๐คทโโ๏ธ I honestly havent used real database stuff in a long time. If my memory is correct, itll just be slower but I guess you could have more "organization". You could also have the exact same data in any other format
Yea I'm personally unsure what you would use for columns and rows etc
a relational database would be useful for recording relationships between different entities in the level, I guess
Vector3.LerpUnclamped I guess
yes, that's what the unclamped variant is for
@waxen light
I'm adding a 3D object to my Unity 2D project with URP. I want to show this dice on top of the UI canvas elements. Would the best way be to just add a new camera for the 3D object separately?
yea seems to work with a new cam
and remove new layer for dice from culling mask of UI camera
I think I figured out the reference frame issue
in LateUpdate(), we move the transform of the child by the displacement of the parent transform since last frame
Hello!
So I am using Netcode and also a random generated maze. The problem is that when I am doing those two things together, it creates a random generated maze for each of the players which make them have different mazes...
Is there a way to make it so I will only create the maze at the host and then build it at the other users too?
(Like copying the parent object of the maze to the others or make it visible for them too)
Hello everyone!
I have an issue with prefab duplication
I have two prefabs, Bullet and PickupBullet, whenever the bullet collides with ANYTHING that has a collider, it will delete itself then instantiate the PickupBullet prefab
What I am trying to do is make the player shoot a bullet, and when the bullet hits anything in the world it will delete itself and spawn a pickup prefab at the location where the bullet hit
However, everytime the bullet collides with an object, the PickupBullet will duplicate twice instead of once.
Below is a video example and links to the script itself for both the bullet and pickupbullet
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.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.
show bullet prefab
this is the whole object? no child objects ?
Yep, the bullet only has the collision and rigid body
The same goes for the BulletPickup prefab
perhaps colliding withmultiple colliders?
I was about to ask how the wall and floor are built
Maybe just add in a member bool and flip it
I already tried adding a delay in instantiating the pickup bullet prefab as I believed that both the Bullet and Pickup collided with each other caused it to do it twice
have you tried putting the pickup and bullet on different layers that do not collide with one another?
Oh it just has a collider, however the ground has a Ground layer
ooh maybe
Yeah it did not work, I created a Bullet Layer and a Pickup Layer however the issue still occurs
Layer itself doesn't do much
is there anything similar to a Scroll Rect for non UI space?
I want to be able to essentially zoom the camera with the scroll wheel to be synchronized with my UI scroll rect
I'm treating a UI map as a "board" with a mix of 2d and 3d objects
Eh, well the scroll rect is a normalized value from 0 - 1
so normalize a distance relating to that
hmm ok
double roundedCandy = Math.Round(candy);
candyText.text = "Candy: " + roundedCandy;```
Making an incremental game, the "candy" variable which is the currency being added to over time is rounding up when it reaches #.5 and I can't have that because it's not precise. I've tried using the Math.Round, Math.Floor, Math.Ceiling, and Math.Abs functions yet nothing changes
i wonder if FOV would work
Does anyone know how I can get this to actually work lol
gonna try that
Just make a bool called "pickupSpawned" or something. Check if it is false before instantiating, and after doing so set it true
Edit: something like this actually:
if (pickupSpawned) return;
instantiate()
pickupSpawned = true;
maybe it's already rounded before you mess with it? did ou console log the output
ill give that a go, ill let you know if it works ๐โโ๏ธ
The candy text on screen shows the rounded text, the candy variable is in the inspector, so I've been looking at those two and it's 100% rounding wrong
I can't buy something that costs 15 while the text says 15 until the actual variable reaches 15, since it's at 14.5 (edited 4 times because my brain's melting)
So you checked the value on the first line and it says candy = 14.5?
does this look good or have I placed it in the wrong place?
The candy variable in the inspector says 14.5 while the physical text I'm displaying it on says 15, because it's rounding in the string
When it's 14-15 it should say 14, I need it to round down
I've tried Math.Floor but it refuses to do anything
did you inspect roundedCandy to make sure it's the value it's supposed to be
i would check with debugger, step through lines to check values
It's the same as the text, I had it as candy.ToString() before this and it was rounding the same way
The inspector changes in realtime lol, I know 100% that it's rounding to the closest whole number
is it possible the TMP textfield is getting overwritten by another script or something afterword?
cuz your code looks fine
No, so I'm confused
Does it being a double have anything to do with it?
You don't need the curly braces after the if statement.
The body of the statement is the "return;" part
But yeah, in terms of order, that is fine
Apparently the string is saying 4, candy is at "3.64187975844834", and roundedCandy is at 3. So the issue is in putting the number to the string
Can your array be modified if you pass it to a method?
oh whoops change type of roundedCandy to int should fix it
Math.Round returns an int
also, you can just use var in c#, it makes things like this trivial ๐
int roundedCandy = (int)Math.Floor(candy);
candyText.text = "Candy: " + roundedCandy;``` Changed it to this and it's still refusing
Had to put the (int) because the regular candy value is a double
Mate you are using floor which rounds it down
Sorry I was wrong, it returns a double
Can it be the issue?
Unfortunely, it did not work
I want it to be rounded down, it's currently rounding to the closest whole number
Can you show the code you have now?
Actually, maybe set the bool BEFORE instantiating
It's rounded down
ill do that then
The string that roundedCandy is being displayed to says 4, yet roundedCandy is at 3
The string is rounding it somehow and ignoring the Math.Floor roundedCandy value
@hexed sleet your original code should have been fine. If you are getting two, is it possible there are two bullets on top of one another and each is spawning it's own pickup?
I think I may have found the issue, whenever I click right mouse button it creates a Bullet clone, however that clone has TWO bullet collision scripts for some odd reason
However when I check the original bullet prefab it only have one script attached
Not sure if thats the problem but let me try getting a snapshot
That explains the duplication. Where do you instantiate the bullet?
It can't be right. Something is wrong with your logic
public void Update()
{
roundedCandy = Math.Floor(candy);
candyText.text = "Candy: " + roundedCandy.ToString();
cpsText.text = "CPS: " + totalCPS;
soulText.text = "Souls: " + souls;
candy += totalCPS * Time.deltaTime;
}```
I instantiate the pickup bullet in the bullet prefab
(aka BulletCollision script for the red bullet, PickupPrefab for the other)
The program's going rogue, refuses to round down
Try debug.logging candy text right after you assigned it
OH I DID IT
I meant where is the bullet itself being instantiated?
oh, great!
Ill explain my issue, I had a seperate player script which I didnt add because I believed it did not affect it
//Attach a script to the bullet to handle collision
bullet.AddComponent<BulletCollision>();
this line added another bullet collision script to the Bullet prefab
however I forgot to remove it due to previous issues I had which I thought that adding that would solve it, which it did, however it caused another issue
thank you all for your help ๐
Yeah, okay, Debug.Log(candyText.text) is passing the correct rounded value, but the actual text isn't 
Why Unity why lol
Obviously because something else changes the text
The only other thing that even touches the candyText.text variable is my options menu, and disabling that has the same exact result
Try removing the text variable and seeing where you get errors
That variable is part of TMP so that wouldn't be possible. And if another script had a reference to the TMP element, that wouldn't show up as an error
@somber nebula is the text incorrect in the TMP component in the inspector?
No external script errors
Text string variable in the TMP component is the same as the text in-game
Try debugging flooring and assigning in on debug.log
It would be fastest to tell Unity to include the TMP project int eh VS solution and throw a breakpoint in the text property
If it's being called from multiple places you'd see it immediately
For the first time I think I'm just gonna give up on it lol, I'm very fairly confident this isn't a problem with anything I've done and I can't be bothered to go search through TMPro code to double check / find out what could be wrong on that side
But thank you all for helping
Just tried, does what it should in the debug.log but the text still doesn't change. Gotta be a problem with TMPro
Or maybe I just need to restart Unity for some odd reason, either way not too big of a deal
Mate, there are no any such bugs in TMPro
TMPro is worked with by numerous people
If you want to, we can have a quick call and I will try to help you
Like I said I'm not too worried about it, but thanks anyway
Ay yall, is learning Unity's Input System worth it?
Absolutely
It looks complicated tho, idk how it can be better compared to the old one
When you want seamless transition from different input devices with ease , rebind etc.
It IS more complicated for sure (while learning it). But it is also vastly superior imo. Once you get it, it's not hard to use. If you understand events work or how SendMessage works, you'll be fine. It's flexible, so you can use it multiple ways (which IS part of what confuses people unfortunately. Knowing which method to use. I like the unity events or c# events method)
You can upgrade to the new input backend with the shortcut APIs like Keyboard.current and Gamepad.current, but you'll miss out on the rebinding stuff of the action mapping system.
Probably less important on the desktop, but I would recommend the new input system on mobile due to some reported input latency issues there.
That's how I eased into it. Doing that for some things and incrementally adding in event based stuff was just fine.
Anyone know what the formula is that Unity uses to apply friction to a body?
you should probably search for PhysX answers instead since unity uses PhysX
can somebody help me? im trying to enable a game object by clicking the key tab, no errors in the output but doesnt work, ```cs
using UnityEngine;
using UnityEngine.InputSystem;
public class LeaderboardEn : MonoBehaviour
{
public GameObject objectToToggle;
private bool isTabPressed = false;
private void Update()
{
if (Keyboard.current.tabKey.wasPressedThisFrame)
{
isTabPressed = true;
if (objectToToggle != null)
{
objectToToggle.SetActive(!objectToToggle.activeSelf);
}
}
if (Keyboard.current.tabKey.wasReleasedThisFrame)
{
isTabPressed = false;
}
if (!isTabPressed && objectToToggle != null)
{
objectToToggle.SetActive(false);
}
}
}
I'm keeping a list of game objects as they enter / exit a trigger 2d collider. some of them might be destroyed, and while enumerating i'm getting the collection was modified, invalid op. How to best guard against this?
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.Generic.List`1+Enumerator[T].MoveNextRare () [0x00013] in <130809ae6f984869a6663c878f16e3f3>:0
at System.Collections.Generic.List`1+Enumerator[T].MoveNext () [0x0004a] in <130809ae6f984869a6663c878f16e3f3>:0
I'm neither removing nor adding them during enumeration. The objects may destroy themselves
Show the full stacktrace
InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.List`1+Enumerator[T].MoveNextRare () (at <130809ae6f984869a6663c878f16e3f3>:0)
System.Collections.Generic.List`1+Enumerator[T].MoveNext () (at <130809ae6f984869a6663c878f16e3f3>:0)
Behaviours.Gameplay.Meridians.MeridianOpener.AbsorbPowerFromQiStats (System.Collections.Generic.List`1[T] qiClusters) (at Assets/Scripts/Behaviours/Gameplay/Meridians/MeridianOpener.cs:28)
Behaviours.Gameplay.Meridians.MeridianController.OnBreathCompleted () (at Assets/Scripts/Behaviours/Gameplay/Meridians/MeridianController.cs:65)
Behaviours.Gameplay.Cultivation.CultivatorBreath.OnBreathCompleted () (at Assets/Scripts/Behaviours/Gameplay/Cultivation/CultivatorBreath.cs:33)
Behaviours.Gameplay.Cultivation.CultivatorBreath.Update () (at Assets/Scripts/Behaviours/Gameplay/Cultivation/CultivatorBreath.cs:27)
What is MeridianOpener.cs:28
It enumerates on a list of objects and absorbs their power
Can you show the !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.
That in addition to other factors can cause the object to run out of power and go poof, but it's not guaranteed that the absorber on its own will do it
{
long allowedMaxAbsorption = Math.Min(AbsorptionPerBreath, meridianController.PowerRequired);
foreach (var qiCluster in qiClusters)
{
var absorbed = Math.Min(qiCluster.Power, allowedMaxAbsorption);
qiCluster.SubtractPower(absorbed);
AbsorbPower(absorbed);
}
}
The call to subtract power can trigger a deletion of the object
What do you do in SubtractPower and AbsorbPower?
Does that remove it from the list?
qiCluster will call Destroy(gameObject) on itself if it runs out of power
That doesn't matter, it's not modifying the list
The list is sourced from the BreathBehaviour, it keeps track of gameobjects as they enter and exit
and is that list being updated when you destroy the object?
So this function gets called by MeridianOpener (implements BreathBehaviour) and passes it in
If I'm not mistaken an object destruction on a trigger 2d will call the OnExit? I'd guess so since that would be the only way for the list to change
I could cache the list and check activeSelf on each object maybe? Not sure how to best cache the list though
internal void AbsorbPowerFromQiStats(List<QiCluster> qiClusters)
{
long allowedMaxAbsorption = Math.Min(AbsorptionPerBreath, meridianController.PowerRequired);
var cachedClusters = qiClusters;
foreach (var qiCluster in cachedClusters)
{
var absorbed = Math.Min(qiCluster.Power, allowedMaxAbsorption);
qiCluster.SubtractPower(absorbed);
AbsorbPower(absorbed);
}
}
Maybe that?
That's the same list, it's a reference type
How can I sever the connection?
would have to copy all the items to the new list
yeah, itโs not really severing. itโs making a whole new thing and pointing to it
Cause what's happening. Ithink is Subtract sets it to zero, triggers destruction, triggers onExit, removes the element from that list and it scaffolds back down into the same method, which goes to do another enumeration
thatโs how reference types work
Afaik Destroy wouldn't immediately call OnExit, because it's deferred
I have no idea what this "OnExit" is though
Hmm
Q: will OnCollisionEnter always be followed by OnCollisionStay or OnCollisionExit?
Destroy happens at end of frame, would call the exit logic first then call destroy after
{
var qiCluster = other.GetComponent<QiCluster>();
if (qiCluster == null) return;
ThisBreath.Remove(qiCluster);
NextBreath.Remove(qiCluster);
}
ThisBreath is what would matter in this case
{
var qiCluster = other.GetComponent<QiCluster>();
if (qiCluster == null) return;
if (NextBreath.Contains(qiCluster))
Log.Warn("A QiStat we're already tracking for next breath has entered again!");
NextBreath.Add(qiCluster);
}
For reference that's the enter (there is no Stay)
Iโm seeing weird behaviour, and trying to figure out if Iโm making a faulty assumption
You may be able to get away with using a reverse for loop instead of the foreach, but I am not totally across your logic, and it seems a bit brittle
In what way?
That you're using a list while something somewhere else entirely can modify it based on events
Hmm, maybe a concurrency bag?
There is no concurrency
it's just a logical error, modifying a collection while using a foreach over it is not allowed
Yeah, but I didn't think it would get modified right away but rather next frame, at which point the enumeration would be over
I'm not sure how it can even change to be honest, I can't see anything else besides that
well, it seemingly Destroy immediately removes it from the physics world, triggering those events. It's not happening at the same time though, to be clear it's all still just on one thread.
Also Destroy usually will just occur later in the frame, not the next frame
You can use the debugger to check if that's actually occuring while you're iterating
I'll have to investigate it further, thanks
Well... it triggers immediately. Didn't know that ๐
DestroyMe is where destruction occurs and it beelines into the OnTriggerExit
if qiCluster is the item that the same item that's being destroyed then a reverse for loop will work, if it's not it'd cause more unpredictable issues.
But that the solution needs to rely on that fact to me speaks to why the setup isn't ideal. You can make it robust by copying the list (into a different cached list) and iterating over that instead, which may be totally fine at this scale
Yeah it should be fine to copy, I can't imagine more than maybe a dozen of items in one list at any time. The question however would be if I'm only doing this to circumvent the enumeration change, the reverse loop gets the same job done for less computation and memory
But I'm definitely taking a note of this quirk
@rigid island
alright so are the logs printing when you try to make purchase?
You're new aand already trying to use an SDK for IAP?
Debug.Log
that prints debugs to the console
one of them is saying you did not Initilize the Oculus features , it tells you which method to use.
second one is you missing something on line 43 of the PlayFabShopManager script at runtime
this? IAP.LaunchCheckoutFlow(skuToPurchase).OnComplete(BuyProductCallback);
if that sline 43 then yes
yea
one of those is null.
probably IAP if services is not Init, I don't use Oculus so I can't really tell you much about it
do u know how to fix it?
You'd have to look through the documentation, I never used oculus before.
im too young for this stuff man
then why are you trying to setup IAP already ?
I need it for my dad
learn how to code a simple game first, get yourself familiar with coding
he has cancer
how would IAP help with cancer? you will probably not make anything from it
you coded a game but don't know how to implement IAP ? how did you code the game then
if you truly aren't trolling and wanna help your pops get a real paying job
dude im 13
Question, how common/acceptable would it be to create a separate tilemap + child maps for collisions and other stuff, for each section of the map in a game (fade screen when switching between areas)
because id want to be able to loop through the tilemaps in a specific area of the map in my game
I don't see an issue here
halp, I did something bad
gonna need a bigger screen
why dont you use for loop if you need index?...
btw i dont see g++ but you use g for checking
I have to make a function that prints one layer that accepts another function
this is unholy af
way too tired to do this right rn
if this was python it would tell you off saying something about cyclomatic complexity ;)
and use stringbuilder
and change the voxel type to be dictionary to save one forloop and increase the performance
i think you want to print some debug message of unique voxel in each chunk and each chunk in superchunk and each superchunk in gigachunk and all gigachunk
oh wait, not, just print out all voxels
preformance is irrelevant, this just formats and copys to the clipboard
dict=new dict<Voxel,int>()
unique_id=0;
inside the foreach loop:
if(voxel.color.w>0&&dict.trygetvalue(voxel,out idx)==false){
dict.add(voxel,unique_id);
unique_id++;
}
else{
//do nothing
}
```i believe it maybe better (at least for me), fewer line, fewer loop
Invalid pass number (0) for Graphics.Blit (Material "(Unknown material)" with 0 passes)
When building and running a Linux Dedicated Server, I see an infinite loop of the following Error thrown in the Console: Invalid pass number (0) for Graphics.Blit (Material "(Unknown material)" with 0 passes). I wish I could ignore this error but it's effecting performance; server is utilizing up to 80% of vCPU when running in a Docker container.
I hope someone can assist. I'm trying to launch a closed beta test of my upcoming game, but I'm totally blocked now due to this issue.
I am quiting Unity
Yes we know you already said that in #๐ปโcode-beginner
It's off topic for both these channels though
I was meant to put it in a other server
Hello, here I unsubscribe typeSelectinoField and its children when the gameObject is disabled, but it throws MissingReferenceException, because typeSelectionField is disabled before that. What should I do?
private void OnDisable()
{
typeSelectionField.onOptionSelect -= SelectType;
foreach (OptionSelectButton option in typeSelectionField.options)
option.attachedObject.GetComponent<OptionSelectionField>().onOptionSelect -= SelectOption;
LevelManager.instance.SaveLevelIfAintPlaying(GameUtility.currLevel);
}
The reference being disabled should not be an issue but rather it's likely that the reference was removed that is the issue.
Maybe show us the actual error with stacktrace
oh, but gameObject shouldn't become null if it's disabled..?
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
oh, destroyed
So you've destroyed it but are still trying to access it
but it's disabled in the inspector, not destroyed
if null
return/ignore/skip etc```
but it's bad if I don't unsubscribe an action ?
You can't unsubscribe anything from nothing
Null doesn't have anything to unsubscribe
It's already been destroyed
I see, it becomes null when I disable its parent
levelCreator.SetActive(!value);
then it becomes not null when I re-enable its parent
On disable function:
Yo dude that has already been marked for destruction. Let me unsubscribe sometime real quick.
Subscription service:
Nope, we're already destroyed. Throwing an access violation error for attempting to modify me.
I see, so I don't have to unsubscribe it if its parent is disabled, right?
this way it's considered as "destroyed" ?
It's not that it's been disabled, it's been destroyed.
its parent is disabled.
A disabled component or inactive object would simply not be calling their callback members. A destroyed object will soon be null - thankful null check considers them destroyed already.
Error implies that it's been destroyed
I see, so it's considered as "destroyed" if its parent becomes disabled
No. The object was destroyed according to the error.
Disable and inactive does not imply destroyed
I don't destroy it though, I disable its parent
But how come? I didn't destroy it.
Not certain if you did or did not but what's what the error is implying.
That's the mystery ๐
well, it's strange...
levelCreator.SetActive(!value);
print($"Active now: {!value}; LevelCreator: {(bool)levelCreator}; typeSelectionField: {(bool)typeSelectionField}");
// output:
// Active now: False; LevelCreator: True; typeSelectionField: True
it isn't null here, but null in OnDisable
the thing is that it's null just when active now is false, that means the game is being played right now
Maybe you've got a "destroy this game object" on inactive/disable etc
sorry, what do you mean?
Do you call destroy anywhere?
I don't call it on this gameObject
on other, yes
Likely that isn't related to the error unless you're destroying when the state of the object changes.
The object was destroyed (not inactive or disabled) when the on disabled callback was fired. The mystery would be why?
who knows.., I just have this OnDisable method on that GameObject
private void OnDisable()
{
onOptionSelect -= SelectOption;
}
Are there more than one script attached to the object?
Did whoever reference and disable the script destroy it?
yes, Unity's HorizonalLayoutGroup and my OptionSelectionField
Who destroyed the object before the callback was made?
Something has destroyed it before the callback was made
No, this #archived-code-general message OnDisable method is called when I change my scene by pressing Home Button in the game
the typeSelectionField is disabled a by that time
(and destroyed)
https://docs.unity3d.com/Manual/ExecutionOrder.html According to the error, someone destroyed it before the callback was made.
Figure out why it was destroyed when it shouldn't have been destroyed or don't modify it after it's been destroyed.
So you've destroyed it..
Then the disabled callback threw the error
it's written in the error ๐ค
I forgot that it's serialized, it is not null until I press Home Button, then it throws me an error (just the game is in play mode and typeSelectionField is disabled)
Some generic question since I stink of this stuff
public abstract class EntityRoutine<SO> : Routine where SO : EntityRoutineSO
{
public SO EntityRoutineSO { get; set; }
public void StartRoutine(IEntity target)
{
target.EffectsManager.AddRoutine(target, this); //problem with passing this exact instance
}
}
public class EntityRoutineManager : MonoBehaviour
{
public void AddRoutine(IEntity target, EntityRoutine<EntityRoutineSO> routine) { }
}
How do I tell the compiler I went to send this instance as this SO type of the current constraints into this function
If you didn't destroy it, figure out why it's unknowingly being destroyed.
I see, I'll try to debug it right now, thank you for your help ๐
Also I assume that if I had a more derived SO type this should still work
A more derived type and SO would be
AbilityRoutine : EntityRoutine<AbilityRoutineSO>```
but I dont care if the manager doesnt know about this more derived type or SO
Maybe try casting this to the explicit type? The abstract ideally wouldn't know anything about it's inheritors though..
maybe I'm not understanding the syntax but IDE doesn't seem to help
What if there was a method like EntityRoutine<SO>.SetSO(SO instance)
Your AddRoutine method would only be able to call SetSO with a EntityRoutineSO
What you have might make sense in the scenario you have set up, but the constraint doesn't actually allow for what you might expect, because of all the scenarios it caters for
Right, but this less derived SO would still work with more derived class/SO, right
because the manager doesn't care about this AbilityRoutine and what it has, only the virtual methods
Because your method is not allowing for "more derived" classes, it cannot function properly with them
But what I'm saying is what if the virtual method took an instance of the derived SO type
how would that even work in this AddRoutine method, the AddRoutine can only see routine.Method(EntityRoutineSO instance)
but the derived class cannot take that, it needs the more derived type
the only way you can do this is if you also have a generic constraint on your AddRoutine method
or, you have add another interface or class that doesn't allow for the generics, like Routine
let me reflect on this. This stuff is a spiderweb and I love digging myself holes
usually I would try other methods, but with unity I have to also please the editor by having the exact serializations
and not being able to serialize interfaces is really hard
You'd need something non built in to illustrate the different members in a collection of some abstract or interface types.
Just to elaborate on what I mean:
public abstract class Example<T> where T : ElementBase
{
public void Method(T target) => ...
}
public static class Foo
{
public static void Bar(Example<ElementBase> example) => example.Method(new ElementBase());
}
Calling
Example<DerivedFromElementBase> test = new();
Foo.Bar(test);
Will try to assign ElementBase to a class that needs DerivedFromElementBase, and this is why you can't set it up like this
Hmm
I forget whether this is something you can do with covariant generics
that sort of thing just confuses me
I've dabbled with covariant stuff and lost my mind over it already
trying to make one of those mmo hotbars with different options (armor -> equip, abilities -> cast, potions -> use)
it was more that I needed to allow these types on the hotbar
I'd do try get component or cast to determine the available options for the hot bar to keep all of the necessary hotbar related code in one place rather than having to explicitly implement special cases for unique abstractions.
yeah the smart way lmao
honestly I feel like I want to rewrite it all and do it like that
the covariant stuff requires basically duplicating your classes into interfaces and it's ugly
public abstract class EntityRoutine<SO> : Routine where SO : EntityRoutineSO
{
public SO EntityRoutineSO { get; set; }
public abstract void StartRoutine(IEntity target);
}
public class AbilityRoutine : EntityRoutine<AbilityRoutineSO>
{
public override void StartRoutine(IEntity target)
{
target.EffectsManager.AddRoutine(target, this);
}
}
public class EntityRoutineManager : MonoBehaviour
{
public void AddRoutine<SO>(IEntity target, EntityRoutine<SO> routine) where SO : EntityRoutineSO { }
}
Yeah, that seems to be the idea
just had to pass it up via virtual
with the constraint
It's unfortunate that the ide/intellisense is pretty useless when it comes to generic errors
What I've seen is, it's either parsing to see what we've got available or implementing the differences per level of abstraction to not have to parse/identify what we've got during runtime ๐ฅน
Is the extra mess/work worth it? Runtime could be simplified a bit with a collection of additive options if needed - decoupling from the type (enum) and instead with inspector-prefab setup. It really depends on the size of the data you're working with, I guess.
I'm always looking for ways around type checking, but sometimes it's just not worth the hassle yeah
was reading that a lot of the covariant stuff isn't even that performant so maybe it was all for nothing rofl
If you've got thousands of items, maybe trygetcomponent and cast would be worth it else predefining these with inspector/variances or inline implementation could be applicable if it's not too much (relative to differentiating options available)
Hey, i've made this simple function
void DeleteSelf()
{
print("I'm removing myself from existence!");
Destroy(gameObject);
print("I'm not removed!");
}
How come the second print statement gets called? I think that if the gameobject is deleted, scripts on it should stop. The gameobject also doesn't get deleted
Well first off Destroy doesn't destroy the object immediately
It cues it up to be destroyed at the end of the frame
Second, there's nothing in C# that would allow a function to make another function stop running in the middle short of throwing an exception
Since Unity s API cannot violate the rules of C#, the code keeps running
It will be destroyed at the end of the frame
but it doesn't, the game keeps running (in a broken state, that is)
If you think it's not, maybe You're calling this function on the wrong object
Instead of print use Debug.Log("your log message", this)
Then you can pause the game mode and click on the message in the console and it will highlight the object that sent the message in the hierarchy
If it's not destroyed, that is
Yeah, just found out that there actually is another gameobject holding that script, and I was dead sure there's only one 
Well, that should fix everything
that is useful, didn't know about the highlighting thing
you can run code on a destroyed object since the instructions are stored separated
Yep, I get it now
I've fixed that, thanks for help guys. Moral of the story: never be 100% sure that something you think you've removed long ago is actually removed.
unsafe private struct A {
int a;
public void AA(A*a_ptr) {
UnsafeUtility.Free(a_ptr,Allocator.Persistent);
Debug.Log("i am called");
}
}
unsafe private A* aPtr;
unsafe void Awake(){
aPtr=(A*)UnsafeUtility.Malloc(4,UnsafeUtility.AlignOf<A>(),Allocator.Persistent);
aPtr->AA(aPtr);
}
if you have multiple objects of same class with public reference to a prefab, is that prefab going to be duplicated in memory or something
i think static keyword would be better if we want to ensure that theres just one copy
no
they're just references to the same object
reference is a pointer pointing to the memory space, the memory pointed by them will not duplicated
Hi all. I want to check for inappropriate images within unity. Is there any sdk available for this?
covariance and contravariance feel evil
How can I determine when my object is moving and when it's not from this update function?
void Update()
{
var trackingPosition = Reticle.transform.position;
if (Vector3.Distance(trackingPosition, transform.position) < 0.1)
{
return;
}
var lookRotation = Quaternion.LookRotation(trackingPosition - transform.position);
transform.SetPositionAndRotation(Vector3.MoveTowards(transform.position, trackingPosition, Speed * Time.deltaTime), Quaternion.Lerp(transform.rotation, lookRotation, Time.deltaTime * 10f))
}
compare the current position to the position you are moving to
if they're different, it's moving
I tried velocity , and it plays walking animation but It wont stop playing the animation when target is reached
here's my code with velocity
void Update()
{
var trackingPosition = Reticle.transform.position;
if (Vector3.Distance(trackingPosition, transform.position) < 0.1)
{
return;
}
var lookRotation = Quaternion.LookRotation(trackingPosition - transform.position);
transform.SetPositionAndRotation(Vector3.MoveTowards(transform.position, trackingPosition, Speed * Time.deltaTime), Quaternion.Lerp(transform.rotation, lookRotation, Time.deltaTime * 10f));
// Calculate the velocity by measuring the change in position over time.
Vector3 currentPosition = transform.position;
Vector3 displacement = currentPosition - previousPosition;
float velocity = displacement.magnitude / Time.deltaTime;
// Update the Animator.
if (velocity > 0.1f) // Adjust this threshold as needed.
{
animator.SetFloat("Walking", velocity);
}
else
{
animator.SetFloat("Walking", 0);
}
// Store the current position as the previous position for the next frame.
previousPosition = currentPosition;
}
what debugging steps have you taken?
I've debugged in the if/else for the animator as well as in the update function outside of if and else statements
ok and what did you log and what did you find when you did that
the else statement doesn't run its debugs
so then that's never happening
right
keep investigating why
checking if velocity is less then 0.1
I see that
keep investigating why the velocity is still considered more than .1
I mean maybe this is a clue? cs if (Vector3.Distance(trackingPosition, transform.position) < 0.1) { return; }
on we are returning out of update if it is
And I can't set the animation to idle before I exit , I've tried that
wdym
if (Vector3.Distance(trackingPosition, transform.position) < 0.1)
{
animator.SetFloat("Walking", 0);
return;
}
why can't you do that?
I'm trying again but it didn't work last night
Ok , then lol It's working now ... Maybe I did something wrong last night, It's working now
Thank you @leaden ice
If two objects are dynamic rigidbodies, will every OnCollisionEnter be followed next frame by OnCollisionStay/Exit?
Iโm seeing weird behaviour and want to know if my assumptions are wrong.
anyone knows if theres a difference in performance between instantiating existing gameobject and instantiating a prefab
(the first option will clone it)
no idea. you'd need to test. the main cost of instantiating is going to be the allocation and initialization (and making future work for GC). I assume it'd be very similar
prefab maybe slower since filei/o
gameobject stored in scene is loaded to ram by reading .scene file i guess
idk will unity loads prefabs into ram when you starting the editor
In my game I save items in levels by their name and position. I use name to get an existing item prefab by its name and to spawn it in the game.
The problem is that I have different items that are derived from ItemsController.cs, e.g. Zombie.cs, Arrow.cs, Hole.cs, Player.cs.
I want not just to save the original prefab, but also to save their fields. But they're different. E.g. moveDirection and moveInterval for an Enemy, moveUnit for the Player.
How am I supposed to save them in the json file? Should I make all those classes Serializable and create a unique itemsData list for every item e.g. ZombieData, PlayerData, GroundData, WallData ?
[Serializable]
public class ItemData
{
public string name;
public Vector3 position;
}
"itemsData": [
{
"name": "Ground 3",
"position": {
"x": -2.0,
"y": 3.0,
"z": 140.0
}
},
...
]
public class Enemy : ItemBehaviour { }
Yeah, usually if it's more than an ID then you need data containers and a specific load manager for each
so like this?
[Serializable]
public class Enemy : ItemBehaviour { }
[Serializable]
public class EnemyData
{
public Enemy enemy;
}
and the same for every item that I've got?
Hmm, why does enemy derive from ItemBehaviour
Maybe Item refers to Object or Entity
oh yeah probably
no, Item refers to the GameObject in the game
so GameObjects that are part of my game
that can be spawned by the player
e.g. Ground (1x1 block), Wall, Zombie, Player, Hole, Arrow...
because ItemBehaviour contains behaviour that all my items should have
Right, so the Item refers to some Object or Entity. Normally an item would be an inventory element or something rather than a world object - although world objects could become items as well (Minecraft).
For a more flexible and maintainable solution, you could add a "special data" object to ItemData and make an interface to populate it
[Serializable]
public class ItemData {
public string name;
public Vector3 position;
public object data;
}
public interface IAdditionalData {
object GetData();
void OnLoad(object data);
}
// generic version to get type safety
public interface IAdditionalData<T> : IAdditionalData {
new T GetData();
void OnLoad(T data);
object IAdditionalData.GetData() => GetData();
void IAdditionalData.OnLoad(object data) => OnLoad((T)data);
}
public class Player : ItemBehaviour, IAdditionalData<int> {
...
public int GetData() => moveUnit;
public void OnLoad(int data) => moveUnit = data;
}
// when you save
if (item is IAdditionalData additionalData) {
itemData.data = additionalData.GetData();
}
// when you load
if (item is IAdditionalData additionalData) {
additionalData.OnLoad(itemData.data);
}
This makes it extremely easy to add persistent data to your items, simply implement IAdditionalData<T> with a serializable type of data
Hey guys, I'm trying to make a simple wack a mole game
When a mole is revealed, I'm starting a coroutine so that after 2s it hides itself into the ground again
However, when the player hammers it, I want it to hide right away!
I've tried StopCoroutine and StopAllCoroutines to stop the "countdown" but it doesn't seem to be working well, any other alternatives I could use?
can anyone help me with a problem??
show current code
how have you implemented Start and Stop Coroutine?
please anyone`??
if you want help you need to ask your question first
my music volume script working in unity but not when i build it
Hopes this makes it easier to understand!
ok so, im trying to make a multiplayer game. so i need a specific package in the package manager. but i cant find the package. what do i do?
click on package unity registery and put it to built in
ok ill try
and after that put it back to unity registery
check for runtime errors with onscreen log or player log file
how do i do that
!logs
Documentation
Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log
Unity Hub
Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs
Hint. To Start and Stop Coroutines
Coroutine cor;
...
cor = StartCoroutine(myMethod());
---
StopCoroutine(cor);
althought it might be UI issue
can you first show your Canvas inspector
it didnt work : (
Ah I didn't know you could save a reference to a Coroutine!
I'll try this, thank you!
i mean how can be the ui when i change the slider in unity music stops and in build dosent\
why does the package not sho up for me in the package manager : (
idk
does the slider move when ur in the build?
yes
anyone know what could be the problem??
my package manager does not have all the packages
i think is something that in the build the variables are not loading properly
because i only have the variable too load when i go into options to change the slider
yes, player has an "inventory", where items are stored, they can place them in the game, then they become world objects
well thats why i said to check for runtime errors
in build
@unborn pewter it might help if you
A) Told us which package you are looking for
B) Post a screenshot of your Package Manager
you can also use this neat asset to check in build for console log
https://assetstore.unity.com/packages/tools/gui/in-game-debug-console-68068
ohhh i founf it out. i need a new version of unity
thank you for your response, I was offline for a while, but player has more than 1 field... (and the number of fields's gonna grow)
why does it say i have 0 bytes when i have like 200
i cant installa newer version of unity : (
did you select the correct drive?
is there a way to get GetComponentsInChildren without parent transform included ?
idk why but for me just more and more problems pop up : (
and idk how to fix any of it
thank you so much : )
the first index of the array is usually the parent so just exclude that
actually I forget now
Still works, you just have to make a struct with the data you want to save and set that as the type
yes, you have to write your own generic method
bro u saved me like 3 hours of my life. thank you so much : )
I see, I will try, thank you ๐
oh wait.. fo course another f"#ing problem!!
noooooooo
idk guys. it just seems like nothing works
is just windows that sucks xD probably
open the logs
also this convo goes in #๐ปโunity-talk
wait i did somthing... and it seems to be working
@rigid island i can t find any errors in logs just this i don t know if this an error " Setting up 4 worker threads for Enlighten."
not sure what i did but ur welcome ๐
which log did you open lemme see
after running the game right?
hmm can you share the music script thing
- show setup
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.
is working in unity bot not when i build it
so ur talking about the PlayerPrefs not loading or just the slider doesnt work
you need to explain what exactly is going on and whats happening instead "doesnt work" doesn't help
we know it doesn't work, thats why you're here
can someone explain why (3 & (-1)) is 3? I would have expected it to be 2.
working with bitshift operators is fine until we have signed numbers -.-
why is the rightmost bit of -1 not 0?
~1+1
I thought the rule is: leftmost bit is 0 if positive. If leftmost is 1, all other bits are complement
thatโs really confusing, so there isnโt a sign bit?
negative numbers are just defined by being really big, is what you are saying?
ie -x = ~x + 1?
there is still a sign bit, you can check it by >>31
INT_MAX is 0x7fff ffff and the leftmost bit is zero
iโm still confused then as to why -1 = ~0
once you come to bit level then sign is meaningless indeed
negative number is defined as ~x+1, but in x=1 case it is just equivalent to ~0
hi
is it possible to mention a text file in a cs class ?
like instead of
public ClassName className;
i wanna say general class or text
public Text openFileAsText;
TextAsset
thanks โค๏ธ
so youโre saying:
-x = ~x + 1.
x >> 31 = sign bit.
yes
ty tina. itโs hard to find good info online because lots of sources conflict because they start talking about different representations
two complement system
one more question if I can: I get (-1) >> 31 = -1. Is this because >> isnโt working on the raw binary?
oh it may be arithemetic right shift
follow up then; Why wouldnโt that be zero?
arithmetic right shift will fill one if you are trying to shift a negative numberelse fill zero on left hand side
so you should >>31 & 1 btw i believe the alu will just check the leftmost bit for < 0 or <= 0 instr
so if x < 0, arithmetic x >> y is: remove leftmost bit of x, logical x>>y, put leftmost bit back in
like, it only operates on the right 31 bits
and 100000โฆ00000 gets automatically changed to -1?
no they just shift the bit but arithmetic is:
0b????.... fill the ? with the original leftmost sign while logical is filling it with 0
ty for your time btw tina. this helps a lot
and whether >> is logical is arithmetic is depend on data type unsigned is logical signed is arithmetic
also depends on the language....
Anyone know if its possible to get the position of the furthest path of a navmesh agent? , im trying to have an npc path towards the player and when he is blocked , he should dig.
Furthest path would be to run in circles for eternity. How would you get a position for that? 
When the NPC doesn't find a path to the player, it tells you in the request you send. Don't know if you mean that.
Is there a path to set as the active path from that request?
You can catch that it failed to get a path to the player, and set another path to dig yeah.
Quick question: if I have two voids: void a(T data) and void a(List<T> data) if I do: a(List<Something>) will it load the first or the second one?
i think the solution to my negative numberproblem is to avoid all bitshift operations on negative numbers lol.
Depends what T is, and btw they are called Methods not voids, void is a return type
Thanks
public static void A<T>(T t){
Console.WriteLine("A t");
}
public static void A<T>(List<T> t){
Console.WriteLine("A tt");
}
public static void Main(string[] args){
A<List<object>>(new List<object>());
A(new List<object>());
Console.WriteLine ("Hello Mono World");
}
```i have tried it, output:
A t
A tt
I think you mean PostProcessVolume
idk will it depends on compiler
am i going about this right? to spawn objects on my map im shooting a ray cast with a 25.0f distance. if it hits then im saying that i want to make a new object (currently a block for debugging) and having it spawn on the network. this lets me spawn them in but the issue is that they spawn in some areas i dont want (like you should only build on ground not on say a floating spot), another issue is i want objects to never collide so im not sure when to do box cast to test the bounds. Any advise? im trying to make it similar to building in holdfast
If unity gets stuck in like an infinite loop, or just one frame that takes super long to calculate, is there a way to just force unity to stop?
Attach the debugger and pause the debugger works afaik.
Does GetComponents return components in the same order as the one they are in in the inspector?
not necessarily so dont rely on it
2018.4 docs say it's reliable but the new ones dont
https://docs.unity3d.com/Manual/InspectorOptions.html#reordering-components
"You can reorder a GameObjectโs components in the Inspector window. The component order you apply in the Inspector is the same order that you need to use when you query components in your scripts."
@knotty sun
That's only since 2020, since you didn't specify an Editor version in your question you got the answer you did
https://docs.unity3d.com/2017.4/Documentation/Manual/UsingTheInspector.html
"The order you give to components in the Inspector window is the order you need to use when querying components in your user scripts. If you query the components programmatically, youโll get the order you see in the Inspector."
It is reliable at least since 2017
So I have the following script:
public class Mediator : ScriptableObject {
private GameObject selectedSprite = null;
public GameObject getSelectedSprite(){
return selectedSprite;
}
public void setSelectedSprite(GameObject o){
selectedSprite = o;
}
}```
And Unity is giving me the error "The variable selectedSprite of Mediator has not been assigned", directing me to UIManager, line 12 (line 11 is void Update()):
```cs
void Update(){
if(mediator.getSelectedSprite() != null){
if(mediator.getSelectedSprite().transform.parent.gameObject.CompareTag("Rocket")){
mediator.setSelectedSprite(null);
openIOPanel();
}
}
}```
Why the error? I WANT the cariable to be null for 99% of the time, and only when it becomes non-null should something be done, at which point it becomes null again.
Is it because GameObject has to be something already extant in the scene?
[Serializable] == [System.Serializable]?
Yes
not quite
using System;
[Serializable]
== [System.Serializable]
in general, using allows you to omit the namespace
using Foo.Bar.Baz;
Foo.Bar.Baz.Buz
Buz
both would work
anyone help me with the menu code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
[SerializeField] private string NewGame = "Level1";
public string NewGameLevel1 { get; private set; }
public void Newgamebutton()
{
SceneManager.LoadScene(NewGameLevel1);
}
}
Don't crosspost
So anyways, hi.
I am having a problem when calling a function using a button (this also happens if I use OnValueChanged from NaughtyAttributes).
The function I'm calling is GenerateIsland: https://pastebin.com/eEwsVLvV
It works fine when I start a new game, the thing is, if I change any value while in play mode, I get very weird generation issues. Like, for example, if I change the seed. However, if I give the same seed outside of play mode, it works fine as it should.
The problem, I assume, is that no new value is being given to the altitude variable, which makes the ocean generation unchanged.
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.
The ocean is a custom tile I made: https://pastebin.com/qJwvG6xu
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You should probably post the whole script...
That's literally the only two functions I have
Anyways, the problem is the altitude variable, as the ocean color is the only thing that doesn't change
it seems I'll have to create two tiles for the ocean then
That's not how you compare tags
Wait, it should work
Weird
Oh. You need to do collider.gameObject.tag
You need to be more specific with "isn't working"
Only one of the objects need a rigidbody
Make sure your player is not kinematic
Does your class happens to be named Collision?
Show the inspector of both the wall and the player
and the whole script
This error usually happens if you have a class named Collision2D
!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.
Did you use Debug.Log inside the method to see if it is really not outputting anything?
Then the problem is with the logic
First try changing jumpsLeft != 0 to jumpsLeft > 0
Use col.gameObject.tag
ye
It worked?
๐
Can anyone able to detect the error in this code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControllerX : MonoBehaviour
{
ย ย public GameObject dogPrefab;
ย ย public float fireDelay = -10.0f;
ย ย // Update is called once per frame
ย ย void Update()
ย ย {
ย ย ย ย fireDelay = 0.1f;
ย ย ย ย // On spacebar press, send dog
ย ย ย ย if (!Input.GetKeyDown(KeyCode.Space) || fireDelay > 0.0f)
ย ย ย ย {
ย ย ย ย ย ย return;
ย ย ย ย }
ย ย ย ย Instantiate(dogPrefab, transform.position, dogPrefab.transform.rotation);
ย ย ย ย fireDelay = 10.0f;
ย ย }
}
Hey everybody. I often get these warnings: "There are inconsistent line endings in the script. Some are Mac OS X (UNIX) and some are Windows."
I'm using Visual Studio as my code editor. I changed Solution Options/Source Code/Code Formatting/C# source code/Text Style/Line endings to "Unix / Mac", but still the same warning.
Your if statement appears to always be true, as "fireDelay" will constantly be updated to 0.1f which is ' > ' than 0.0f
You also don't have to put the decimal. You could do -10f, 0f, and 10f. Either way is fine, but just a tip.
Hello, I am trying to set the resolution of my game to always maintain the same aspect ratio. Is there a way to do this immediately on game load?
I tried using Screen.SetResolution in a method with this tag: [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
But the resolution doesn't change until the first frame is rendered. I'd like to set this before the splash screen.
You're setting fire delay to 0.1 each frame so it will always be greater than 0
How can I change the name of my project? I had changed the path to my project but it's exception info still directs to the former one.
I know this question should not appear in this channel, but I really don't know where to post it
In project settings there's a product name
I had changed that
Those are the only things you need to change. Product name and the project directory name.
Are you doing Android perhaps? That has additional settings too like bundle name
I mean the path here. It now shows the former path.
Nope, it's a windows game
Which thing is wrong? The file path?
Sounds like you need to recompile or you still have the old copy of the editor open or something
Or do you mean the namespace of your class?
Yeah, it shows a path that does not exists.
No, the namespace is correct
But I didn't enable burst compile in my editor. How can I force editor to recompile every script?
Oh, wait. I just deleted all the .meta files and reloaded the project. Won't it recompile every script?
That will break most of your references
Making any change to code should trigger a recompile (make sure it's in the assembly with the issue though)
I prefer to assign them in code. So my project didn't crash
Ok, it works. Thanks for your help.
Still haven't solved this issue.
On the Update() method, on line 12, there is no selectedSprite variable. But the error mentions that variable.
Make double sure this code and error message are up to date
Because that doesn't really seem correct
Agreed
Are there any cool ways for creating a prefab, passing a variable and calling a method on it?
- I have:
Instantiate(prefab).getcomponent<script>().Create(parameter);
- I also have a static class version:
StaticClassCar.Create(prefab, variable );
static public void Create(GameObject prefab, Variable variable ) { }
But i think its weird how i have to pass the prefab Which way is better guys ?
NVM im going with the first way
prefer first , 2 return nothing and you have no way to get the return value from instantiate nor getcomponent nor the create() on the component
I use static constructors usually, but now that i've got a lot of object pooling usually I just have some assign function on my objects
Hello so I have this checkpoint script which does work as intended in dev mode but it does not when playing it as a build not to sure why on build it does not work, checkpoint's box collider is set as a trigger
private RespawnScript respawn;
void Awake()
{
GameObject.Find("Player");
respawn = GameObject.FindGameObjectWithTag("Respawn").GetComponent<RespawnScript>();
DontDestroyOnLoad(this.gameObject);
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.name == "Player")
{
respawn.respawnPoint = this.gameObject;
}
}
so the checkpoint is supposed to save data while the player goes into another scene and then returns to the scene with the checkpoint
Did u make sure your scenes are imported
And u used the right indexes
Or maybe you loaded them with they're name
I use a persistent scene loader so it saves it when the player collides with it, when you mean imported do you mean in the build settings or something else?
yep all present
Hello, does anyone have an idea how to implement this kind of selection in my game? (like in Photoshop)
How is it done? I know how to select space, but I want to know how to draw those lines. ( - - - - )
Just an outline shader with white space in between I guess.
outline shader?
I see, do this lines have a fixed size?
But then with another pass that does not only do 100% lines, does it staggered
It's your shader party, you can do whatever you want
You can make the size the whole screen if that makes you happy 
I mean, the closer you're to the screen, the more lines you see in Photoshop
Yeah, that all works in shaders. It's up to you to make that in shader graph though, I don't know if there is an asset that already does this
Maybe you have any useful documentation or a video for this stuff?
But atleast you have the term you are probably looking for.
what term ?
Outline shaders, there are wholes swathes of 3d and 2d tutorials on this.
Great, I will have a look on that, thank you ๐
I am going back to Unity again
How do I make a rect from the mouse position? It is drawn with completely different position
startPosition = Input.mousePosition;
selectionRect = new Rect(startPosition.x, startPosition.y, 100f, 100f);
private void OnGUI()
{
if (isSelecting)
{
GUI.Box(selectionRect, string.Empty);
}
}
Vector2 mouse = Input.mousePosition;
rect = new Rect(mouse.x, Screen.height - mouse.y, 100, 100);
It works, thank you! ๐
Hello, I have 2 questions. Here's the context: when switching weapon, the weapon gameobject that is tied to the player gameobject changes, so when the player shoots or reloads or anything, it reads the properties of the weapon gameobject (ammo, damage, reload time and so on.).
Now, when switching weapon, I also need to update the GUI, so I was thinking about 2 implementations:
-
For example, inside the code that deals with switching weapon, I also put the code that modifies the GUI, meaning I need to get the GUI components (texts and images). Thing is, I separated the code of each actions (shooting, reloading, switching and so on.), which means I'll have to get GUI components on each scripts and I don't know how to feel about it.
-
I try to implement an event system, in which if the player switches weapon, it emits an event, and all the listeners of that event capture it and launch some code of their own.
So the 2 questions are :
is 2) even possible to implement?
Assuming it is possible, is it better than 1) ?
Alternatively, you can have the MVC pattern.
Your weapon would be the model, the controller would be the one that reads out the weapon and update the UI, the View would be the widget that compose the UI. (Label, Panel, Animation, etc.). In my opinion, such implementation is more stable and less complex than event. That being said, event is definitely a way to achieve that.
The difference would be:
In an MVC setting, you would read out the Ammo of your gun each frame to update its value.
In an event setting, you would subscribe whenever the Ammo of the current gun is being updated.
Event system is definitely more performant, however you need be careful because you also needs to listen to event such as when the weapon change.
I created a weapon system which includes both hit scan weapons and physical projectile based weapons. When a projectile hits an interactable object, it damages the object and applies a force on it depending on one of two things: how long it took the projectile to hit something(for the shotgun pellets) or how close the projectile was to the object when it exploded(for the cannonball).
The problem is that the force that pushes the interactable objects seems to be too great but this wasn't a problem before.
You can find the script here: https://pastebin.com/7vinQHAJ
It has to do with the way I move the projectiles. Before, I moved the projectiles by using Transform.position(the commented lines of code) but now I move them using the Rigidbody.MovePosition().
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.
This is the behavior when I use Rigidbody.MovePosition().
This is the behavior when I use Transform.position.
Could somebody help me understand why using Rigidbody.MovePosition() instead of Transform.position is causing the force applied on the interactable objects appear greater?
You do not want to use Transform.position in any form for physics.
MovePosition is not really sutable for the usage you have.
You should use Rigidbody.AddForce(); or Rigidbody.velocity.
The projectiles have kinematic rigid bodies so I can't apply forces on them or change their velocity.
Also, rigidbody.MovePosition should be use in FixedUpdate
Why is that ?
When I innitially started working on the weapon system, I thought that non-kinematic rigid bodies would be risky to work with as they can be affected by other rigid bodies.
You are the one that decide whatever affect it.
With physics layer
True but do you think this is what's causing the behavior?
The behavior of the projectile is inside an IEnumerator method. Inside the coroutine, there is a while loop that waits for fixed update before moving the projectile.
No idea, I suspect that using Transform.position fucks with the physics.
I have no idea how it actually behave with the Physics, however there is little to no reason to use Coroutine here. You can simply use the Update function.
Seems overcomplicated. Why not just give it velocity
No need to be doing something every frame for every projectile
@leaden ice, here.
Make them dynamic
You mean non-kinematic?
I always referred to them as kinematic and non-kinematic. Thank you.
I will make the rigid bodies dynamic but could you please teach me why is this the reason of the change in behavior?
It will let you delete 90% of your code, improve performance, and give you better behavior.
Oh, no, I get that. I meant to ask why does using a kinematic rigid body cause this behavior to occur.
Anyone know how to fix this
!learn
๐งโ๐ซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
You disabled your collider
So of course it doesn't collide
can anyone help me with something??
You can just ask directly. ๐
i can not drag my player in here
do you know the problem??
ive been stuck on this for like 1hour
That object doesn't have a NetworkPrefabList component on it
Which is what your field wants
idk
um can i screen share in a vc then you can help??
No
ok
Just explain in English what you're trying to accomplish
im trying to make a multiplayer game. and to spawn in my player i need to put my player in this prefab list
You made a list of prefab lists
Or an array of them
Sounds like you just meant to have a single network prefab list
Aka you declared the variable incorrectly
yea, but acording to the vid i need to drag into the network prefabs list
Go back
but i can try it without
ok
Generally the type of the object has to match the field it's being dragged into
ill try double checking the vid
i tried whatching the vid again but it still doesn't work
Without further context it's not really something I can help with
The only things that can be dragged into that list are network prefab lists
If your player doesn't have that, it can't go there
You're either dragging the wrong thing in or you missed putting something on the player
it does have the network object script on it tho
true
It's also possible the tutorial you are following is using a different version of the network framework or something
Things might have changed
Best to use the same version of everything as the tutorial otherwise there's a risk of things being slightly different
Hey guys I have a question, how can I make a script that makes every device check the current time in London and if the time is midnight it does something?
The same answer as when the question was about Italy
Oh right I already did the question, but I don't remember getting any answers
Oh yea I just noticed
I see, thanks for the insight !
Suppose I have a parent class that is generic. Child1 : Parent<Child1>, Child2 : Parent<Child2>,
Parent is abstract and has static variables that I want to be shared across each child class (Child1/Child2 should both share the same access to static variable Parent.MyVariable). Any suggestions on how to do this?
Hello, does somebody know what I should use to do this kind of selection in Unity? Are those Meshes, Rect transforms, or what? How do I combine them? (this's from Photoshop)
The number of dashes also isn't fixed. There're more dashes when you get closer
Are you talking about tiles?
or just making that shape
no, I am talking about the full selection behaviour
it's just a random shape to show what I mean
I have to be able to draw this stuff not just in a rectangle form
those lines are just on the borders of the shape
perhaps, just "how to make a solid line to cover any shape (a border)"
you shouldn't apologize ๐ I'm just asking anyone who may know it ๐ค
I've tried to find some tutorials on the web, but that wasn't what I needed
I have also tried GUI.Box, but it draws screen space rectangle
@steady moat, you meant FixedUpdate() here, right?
If you are using MovePosition, yes. However, you should really use Rigidbody.velocity
You only need to set velocity once
Ignore the message in Debug.Log(). I'm tired. :)))
Also, you can use OnTriggerEnter/OnCollisionEnter for collision
I'm doing that already.
Then why raycast
any1 know why this doesnt wokr
Well, since the projectile moves at a fixed timestep, there is a chance it might go through very thin objects without detecting them so I cast a ray from the previous position to the current one in order to compensate for such situations.
Does it make sense?
dont crosspost
Use extrapolation/interpolation setting
If by that you mean I should set the Interpolation of the rigid body to Interpolate, I did that already.
so maybe just create the squares first which should be easy then find the edges/boundaries
https://stackoverflow.com/questions/72998996/drawing-the-outermost-boundaries-of-set-of-squares
Oh, I see. Wouldn't this have a greater impact on performance?
Oh, that seems to solve my task. Thank you. Hope it won't be too expensive to do every frame.
Do you think that shooting a ray each frame would be better ?
Let me know how it turns out
sure.
I'm not sure. That's why I asked.
Also, I moved the line of code where I set the velocity of the projectile out of the while loop and I still get weird behavior when the projectile hits a box.
I should mention that when the projectile hits the object, the force applied to set object is of type Impulse and it has a value between 1.25 and 3.75.
oh sorry
So I set the collisions detection to Continuous for the boxes and Continuous Dynamic for the projectiles and now I get consistent behavior. ๐ ๐ ๐
@steady moat, thank you so much! ๐ค
how do i keep music playing whie changing scenes
if i put physics into a fixed update funktion, will it be frame rate independend(for example you wont move faster with more fps or the other way arround) ?
DDOL
Yes, that's why physics applied over time (like with AddForce) should always be in FixedUpdate
Okay
yo can some1 help me with my playermovement/damage script
i've got this like damage thing
and i want it to knockback when it hits the spikes
but it only knockbacks upwards
and not back
should i send the whole script
maybe in like pastebin cuz its too long
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
its at line 53
like the function
oh and i didnt mention its 2d
You override horizontal velocity in FixedUpdate so the knockback gets undone there
ohh
how can i fix it
Don't set velocity directly to move. Use AddForce.
it worked but its like slidey n slippery n shit
oh wait is it the forcemode thing
oh uhh
The default force mode is correct. You'll have to adjust the amount of force, drag and friction until it feels right
You can also start a coroutine to add knockback and disable velocity setting. Then when the coroutine is done, go back to normal movement
That's a common way of handling that
ok thx
sorry to bother you, they use gizmos in that answer, but it's not visible for the player, are you aware of any way to draw the line so that the player'll see it?
use line renderer
or GL potentially
looking for help with some buoyancy physics. i found this (seemingly) great pipeline that has an outdated tutorial i'm trying to get to work. has anyone used this? :https://www.habrador.com/tutorials/unity-boat-tutorial/2-basic-scene/
This is a tutorial on how to make a realistic boat ship in Unity with boat physics like buoyancy and water physics. You will learn how to make and endless infinite ocean, add water foam and water wakes, add boat resistance forces, add propulsion, buoyancy so the boat ship can float, and much more. Everything is made with the programming language...
here's a newer repository with a sample scene that doesn't work: https://github.com/Habrador/Unity-Boat-physics-Tutorial
i'd love to reverse engineer it but it's busted
Guys, I want to use this code snippet but I can't add the JavaScriptSerializer from which library does it belong to?
are there any watchouts I should know about with respect to structs and interfaces?
When assigned to an interface type, local variables of a struct type are boxed (put onto the heap) which can be expensive if done a lot
Similar to converting any struct to object
I've searched several ways, but it won't let me import the System.Web.Script library
That thing is deprecated, use a JSON serializer that can support root collections types such as Newtonsoft.Json
!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.
how serious should I take the principle of least privilege for unity? Is it fine if i just open up set accessors to classes that aren't ment to use them and such stuff?
For the user who asked about saving scriptable objects - Scriptable objects should not be used to store data that can be mutated (changed). Use a normal class that does not inherit from anything (POCO - Plain Old CLR Object) and save that to a file using your usual serializer.
its good practice
everything should be private for the most part but yeah stick to properties if you need to grant access outside
i just stick to public, if none or lazy evaluation on that variable is required
I see, for instance I try to use some kind of view model controller pattern, and sometimes there I have properties than can be changed by other model classes and be monitored by the view. Is there any clean way there to maintain the principle of least privilege, or should I just throw it and use public setters
thanks, I'll try this
What is the code equivalent of doing this at runtime? (alt+shift pressed)
Get max screen space on the x then shift pivot to it?
Would that change the position too?
if you want it to. You can use another game object as a pivot or calculate the dimensions of your window and work it out
But yeah, get screen space of x, and y/2
You can probably find some similar tutorials implementing tooltips
sorry if im interrupting a conversation rn but i have an issue with physics, i have a player that is composed of a bunch of cube that are their own object. i made it so that they all work with my player's rigidbody and it handles collision as i want. the issue is that when i rotate (especially fast), some of my cubes go through nearby walls. i tried putting my player's rigidbody to continuous collisions but it didnt change anything. can someone help me?
hi , I have problem ,when I add script component and try to start the game , the script deleted and hidden in object then the game start
how are you rotating it?
are you perhaps destroying the component in Start or Awake?
Quaternion targetRotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(cibleRotation), vitesseRotation); joueurRB.MoveRotation(targetRotation);
it's in fixedUpdate btw
is the rigidbody kinematic?
probably moving transforms
joueurRB.MoveRotation(targetRotation); shouldn't work if you've frozen the rotation. so you're probably rotating it via the transform somewhere
It cannot rotate because you checked these three:
Because something uses the Transform to rotate other than the rigidbody
Or a parent/child object rotates
well my cubes dont have any script to move, they all just follow the player's movement
so they dont have collisions following player?
i must be missing somehting
is that what ur asking
they are basically just additional colliders for the player
rect tf.anchorMax=some vector2, rect tf.anchorMin=some vector2
you may have to set the offset min and offset max as well
@elfin tree
when I drop enemy once it never follows me back only ascends to air and rotate randomly
no , its just like this to make object move,
void Start()
{
rb.useGravity = false;
}
// Update is called once per frame
void Update()
{
rb.useGravity = true;
rb.AddForce(2000 * Time.deltaTime ,0,0);
}
I find some problems is unity consle
!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.
NullReferenceException: Object reference not set to an instance of an object
cup.Update () (at Assets/cup.cs:19)
@somber nacelle
show the contents of cup.cs
can I send it here?
yeah but Large Code Blocks
#archived-code-general message
you never assign to rb. also for future reference, always start debugging with the first error in your console. not the last
and your code hiding the gameObject property inherits from monobehaviour
child collider doesn't care about your parent rigidbody rotation
it phase thru stuff
is there some way that i could make it work?
actually hold on , it depends on the speed too
just tested it
yeah at low speed it's fine but when turning at the speed that i want it goes throught the walls
yeah the child might still using transform to rotate/follow parent rotation
the component removed auto because of bugs
i get that, i just dont understand where i would have done that
also rn im debugging code that my friend wrote so im kinda lost in his things
trying different settings :\
can someone take a look at my thread
In my character controller, when I for example strafe and switch from A to D, then the movement completely stops and goes to the other direction, this isnt smooth.
How do I fix this
Depends on how you move right now.
transform.position += ?
Or something else?
charactercontroller.move
Ahhh, using the actual cc component. I have very little experience with it.
What do you put IN the move call though? Where do the parameters come from? Old input or new? If old, GetAxis or GetAxisRaw or GetKey or what?
GetAxis
imma reopen my script
float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); Vector3 move = transform.right * x + transform.forward * z; cC.Move(move * speed * Time.deltaTime); velocity.y += gravity * Time.deltaTime; cC.Move(velocity * Time.deltaTime);
exactly like the brackeys tutorial
Well GetAxis has smoothing already, so I guess suggesting that won't help haha.
I do see you call cC.Move twice though
yes one is for gravity, one for movement
That shouldn't be the issue, but you should only call it once. Add the gravity to your move vector and call it at the same time
Yeah, that's another classic Brackey issue we see a lot. It's bad form
I need help with
[HarmonyPatch(typeof(Character))]
public class CharacterPatch
{
static int jumps = 2;
[HarmonyPatch("AddInputMotionNormal")]
public static void Prefix(Character __instance)
{
if (!__instance.OnGround && jumps > 0 && __instance.input.aButton)
{
__instance.velocity.y = __instance.jumpVel;
jumps--;
}
if (__instance.OnGround && __instance.input.down)
{
Console.WriteLine("Presing down on ground");
foreach (var obj in Resources.FindObjectsOfTypeAll<GameObject>())
{
int owp = LayerMask.NameToLayer("OneWayPlatform");
if (obj.layer == owp)
{
Console.WriteLine("Object is onewayplatform");
var box = __instance.gameObject.GetComponent<BoxCollider2D>();
box.transform.position += new Vector3(0, -0.2f, 0);
if (__instance.gameObject.GetComponent<BoxCollider2D>().IsTouchingLayers(owp))
{
box.transform.position += new Vector3(0, 0.2f, 0);
Console.WriteLine("Moving down");
__instance.transform.position -= new Vector3(0, 99, 0);
}
}
}
}
}
this works V ```
Console.WriteLine("Presing down on ground");
foreach (var obj in Resources.FindObjectsOfTypeAll<GameObject>())
{
int owp = LayerMask.NameToLayer("OneWayPlatform");
if (obj.layer == owp)
{
Console.WriteLine("Object is onewayplatform");
var box = __instance.gameObject.GetComponent<BoxCollider2D>();
box.transform.position += new Vector3(0, -0.2f, 0);
but Console.WriteLine("Moving down"); doesn't
I FIXED IT
well
not the brackeys issue
but
Had to uncheck "snap" in the project settings
Ahhhh right. Thanks for checking back. I'll remember that for anyone else asking!
help?
k
Do you see Object is on Platform?
yes i just doesnt move down
I would put a breakpoint on that if statement containing "Moving Down" to see what the values are in the debugger
Hey again, I was wondering if I should worry performance-wise about events being fired very very quickly. Let's say I have a crazy futuristic weapon that can shoot like more than 1000 rounds per seconds, is it okay to have that many events in such a short moment ? (each event updates the GUI ammo text).
If it's a terrible idea, what is the best way to handle that ?
Whenever you are talking about performance, the best is to actual do it and then profile. I am 99% sure that it wont affect performance and if it does it wont be for the reason you are worried for.
In your case, if your event fires less than once a frame, then it is still a gain to use event and not update loop.
Your frame rate likely won't even be that high
Anyway there's no significant performance difference between an event and a normal method call
You are right, however with event you might find yourself updating more than necessary.
is it possible to detect if an object is within your Frustum Gizmos FOV?
private void OnDrawGizmos()
{
if (!drawGizmos) return;
// Draw the enemy's FOV Via Drustum
Gizmos.matrix = enemyViewPoint.transform.localToWorldMatrix;
Gizmos.color = enemyFOVcolor;
Gizmos.DrawFrustum(Vector3.zero, enemyFOV, enemyMaxFOVDistance, enemyMinFOVDistance, enemyMaxFOVAngle);
}
Alrighty, I'll keep these in mind. Thanks, both of you ! Super helpful 
if the point is between 0 and 1 its in.
would that not require using a camera on the enemy, im going to have a lot of enemies around the world so that would hit performance massively no?
What you are trying to do ?
have an enemy FOV, so if the enemy can see within the Frustum the player will be spotted
Then just compare the angle.
What do you mean?
With Ray casts?