#archived-code-general

1 messages ยท Page 199 of 1

leaden ice
#

the most accurate way to do this would be to use multiple physics scenes

#

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

hard viper
#

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

leaden ice
hard viper
#

that sounds very important for what I need then. To not change from MovePosition

heady iris
#

it is response for changing the object's position

leaden ice
#

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

hard viper
#

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

heady iris
#

So what are you currently doing, and in what way is it malfunctioning?

hard viper
#

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

leaden ice
heady iris
#

Perhaps the platform can advertise its velocity, and then the player can add that velocity to its own MovePosition call

leaden ice
#

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

hard viper
#

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

leaden ice
#

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

heady iris
hard viper
#

I'm going to try fen's idea first, since it sounds promising.

heady iris
#

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

hard viper
#

OnConnectToPlatform: playerRb.velocity += platformRB.velocity;
While connected: playervelocity += (platform velocity) - (last frame platform velocity)
When disconnected subtract

heady iris
#

(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

hard viper
#

I would need to separately program it to have a velociy in the first place

heady iris
#

yeah, that sounds reasonable

hard viper
#

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

heady iris
#

it is a very common concept, yes

hard viper
#

because it is so common

heady iris
#

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

hard viper
#

in real world. but most tutorials don't use friction

heady iris
#

if you're using a rigidbody, then you have friction

hard viper
#

the tutorials do not rely on friction to work, is what I mean

naive swallow
#

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?

heady iris
#

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

naive swallow
#

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

hard viper
#

Q: Does MovePosition work properly on dynamic rigidbodies?

warm stratus
#

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?

lean sail
warm stratus
lean sail
heady iris
#

a database doesn't seem appropriate here

#

you've got a bunch of separate levels

lean sail
#

Yea I'm personally unsure what you would use for columns and rows etc

heady iris
#

a relational database would be useful for recording relationships between different entities in the level, I guess

warm stratus
#

Vector3.LerpUnclamped I guess

heady iris
#

yes, that's what the unclamped variant is for

warm stratus
#

@waxen light

scarlet kindle
#

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

hard viper
#

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

dreamy elm
#

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)

hexed sleet
#

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

https://pastebin.com/tWntJpR4
https://pastebin.com/K9CXqC4s

hexed sleet
rigid island
hexed sleet
#

Yep, the bullet only has the collision and rigid body

#

The same goes for the BulletPickup prefab

latent latch
#

perhaps colliding withmultiple colliders?

proven plume
#

I was about to ask how the wall and floor are built

latent latch
#

Maybe just add in a member bool and flip it

hexed sleet
#

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

proven plume
#

have you tried putting the pickup and bullet on different layers that do not collide with one another?

hexed sleet
#

ooh maybe

#

Yeah it did not work, I created a Bullet Layer and a Pickup Layer however the issue still occurs

rigid island
#

Layer itself doesn't do much

scarlet kindle
#

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

latent latch
#

Eh, well the scroll rect is a normalized value from 0 - 1

#

so normalize a distance relating to that

scarlet kindle
#

hmm ok

somber nebula
#
        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
scarlet kindle
#

i wonder if FOV would work

somber nebula
#

Does anyone know how I can get this to actually work lol

scarlet kindle
#

gonna try that

spring creek
scarlet kindle
hexed sleet
somber nebula
#

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)

scarlet kindle
hexed sleet
somber nebula
#

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

scarlet kindle
#

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

somber nebula
somber nebula
scarlet kindle
#

cuz your code looks fine

somber nebula
#

Does it being a double have anything to do with it?

spring creek
somber nebula
#

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

orchid bane
#

Can your array be modified if you pass it to a method?

scarlet kindle
#

Math.Round returns an int

#

also, you can just use var in c#, it makes things like this trivial ๐Ÿ™‚

somber nebula
#
        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

orchid bane
#

Mate you are using floor which rounds it down

scarlet kindle
#

Sorry I was wrong, it returns a double

orchid bane
#

Can it be the issue?

somber nebula
spring creek
somber nebula
#

The string is rounding it somehow and ignoring the Math.Floor roundedCandy value

proven plume
#

@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?

hexed sleet
#

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

proven plume
#

That explains the duplication. Where do you instantiate the bullet?

orchid bane
hexed sleet
somber nebula
#
    public void Update()
    {
        roundedCandy = Math.Floor(candy);
        candyText.text = "Candy: " + roundedCandy.ToString();
        cpsText.text = "CPS: " + totalCPS;
        soulText.text = "Souls: " + souls;

        candy += totalCPS * Time.deltaTime;
    }```
hexed sleet
#

I instantiate the pickup bullet in the bullet prefab

(aka BulletCollision script for the red bullet, PickupPrefab for the other)

somber nebula
#

The program's going rogue, refuses to round down

orchid bane
hexed sleet
#

OH I DID IT

proven plume
#

oh, great!

hexed sleet
#

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 ๐Ÿ‘

somber nebula
#

Why Unity why lol

orchid bane
somber nebula
#

The only other thing that even touches the candyText.text variable is my options menu, and disabling that has the same exact result

orchid bane
proven plume
#

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?

somber nebula
somber nebula
orchid bane
proven plume
#

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

somber nebula
#

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

latent latch
#

You could just cast to a int too

#

if you want to round down

somber nebula
#

Or maybe I just need to restart Unity for some odd reason, either way not too big of a deal

orchid bane
#

TMPro is worked with by numerous people

#

If you want to, we can have a quick call and I will try to help you

somber nebula
orchid bane
#

Like it's 100% in your code

#

But okay whatever

desert mason
#

Ay yall, is learning Unity's Input System worth it?

rigid island
desert mason
#

It looks complicated tho, idk how it can be better compared to the old one

rigid island
spring creek
# desert mason It looks complicated tho, idk how it can be better compared to the old one

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)

oblique spoke
#

Probably less important on the desktop, but I would recommend the new input system on mobile due to some reported input latency issues there.

spring creek
wispy wolf
#

Anyone know what the formula is that Unity uses to apply friction to a body?

swift falcon
swift falcon
#

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);
    }
}

}

crisp minnow
#

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  
crisp minnow
quartz folio
#

Show the full stacktrace

crisp minnow
#
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)
quartz folio
#

What is MeridianOpener.cs:28

crisp minnow
#

It enumerates on a list of objects and absorbs their power

quartz folio
#

Can you show the !code

tawny elkBOT
#
Posting 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.

crisp minnow
#

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

quartz folio
#

What do you do in SubtractPower and AbsorbPower?

quartz folio
crisp minnow
#

qiCluster will call Destroy(gameObject) on itself if it runs out of power

quartz folio
#

That doesn't matter, it's not modifying the list

crisp minnow
#

The list is sourced from the BreathBehaviour, it keeps track of gameobjects as they enter and exit

quartz folio
#

and is that list being updated when you destroy the object?

crisp minnow
#

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?

quartz folio
#

That's the same list, it's a reference type

crisp minnow
#

How can I sever the connection?

quaint rock
#

would have to copy all the items to the new list

hard viper
#

yeah, itโ€™s not really severing. itโ€™s making a whole new thing and pointing to it

crisp minnow
#

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

hard viper
#

thatโ€™s how reference types work

quartz folio
#

Afaik Destroy wouldn't immediately call OnExit, because it's deferred

#

I have no idea what this "OnExit" is though

crisp minnow
#

Hmm

hard viper
#

Q: will OnCollisionEnter always be followed by OnCollisionStay or OnCollisionExit?

quaint rock
#

Destroy happens at end of frame, would call the exit logic first then call destroy after

crisp minnow
#
        {
            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)

hard viper
quartz folio
#

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

crisp minnow
#

In what way?

quartz folio
#

That you're using a list while something somewhere else entirely can modify it based on events

crisp minnow
#

Hmm, maybe a concurrency bag?

quartz folio
#

There is no concurrency

#

it's just a logical error, modifying a collection while using a foreach over it is not allowed

crisp minnow
#

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

quartz folio
#

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

crisp minnow
#

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

quartz folio
#

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

crisp minnow
#

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

gentle canyon
rigid island
gentle canyon
#

um

#

wat does that mean

#

srry im kinda new

rigid island
#

You're new aand already trying to use an SDK for IAP?

#

Debug.Log

#

that prints debugs to the console

gentle canyon
#

ohh

#

one second ill check

#

@rigid island

#

Do you know @rigid island

rigid island
# gentle canyon <@968604165150507078>

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

gentle canyon
#

this? IAP.LaunchCheckoutFlow(skuToPurchase).OnComplete(BuyProductCallback);

rigid island
#

if that sline 43 then yes

gentle canyon
#

yea

rigid island
#

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

gentle canyon
#

do u know how to fix it?

rigid island
gentle canyon
#

im too young for this stuff man

rigid island
#

then why are you trying to setup IAP already ?

gentle canyon
#

I need it for my dad

rigid island
#

learn how to code a simple game first, get yourself familiar with coding

gentle canyon
#

he has cancer

rigid island
gentle canyon
#

money

#

My game is semi famous

rigid island
#

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

gentle canyon
#

dude im 13

rigid island
#

so?

#

i was working at 13

#

mowing lawns or plowing snow, find something

hybrid orchid
#

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

foggy cipher
#

halp, I did something bad

latent latch
#

gonna need a bigger screen

fervent furnace
#

why dont you use for loop if you need index?...

#

btw i dont see g++ but you use g for checking

foggy cipher
rigid island
foggy cipher
#

way too tired to do this right rn

latent latch
#

if this was python it would tell you off saying something about cyclomatic complexity ;)

fervent furnace
#

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

foggy cipher
fervent furnace
#
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
swift falcon
#

error 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.

umbral radish
#

I am quiting Unity

simple egret
#

It's off topic for both these channels though

umbral radish
#

I was meant to put it in a other server

gray mural
#

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);
}
dusk apex
#

Maybe show us the actual error with stacktrace

gray mural
gray mural
#

oh, destroyed

dusk apex
#

So you've destroyed it but are still trying to access it

gray mural
#

but it's disabled in the inspector, not destroyed

dusk apex
#
if null
    return/ignore/skip etc```
gray mural
dusk apex
#

You can't unsubscribe anything from nothing

#

Null doesn't have anything to unsubscribe

#

It's already been destroyed

gray mural
#

I see, it becomes null when I disable its parent

levelCreator.SetActive(!value);
#

then it becomes not null when I re-enable its parent

dusk apex
#

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.

gray mural
#

this way it's considered as "destroyed" ?

dusk apex
dusk apex
#

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

gray mural
#

I see, so it's considered as "destroyed" if its parent becomes disabled

dusk apex
#

Disable and inactive does not imply destroyed

gray mural
dusk apex
#

But how come? I didn't destroy it.
Not certain if you did or did not but what's what the error is implying.

dusk apex
gray mural
#

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

dusk apex
#

Maybe you've got a "destroy this game object" on inactive/disable etc

gray mural
dusk apex
#

Do you call destroy anywhere?

gray mural
#

on other, yes

dusk apex
#

The object was destroyed (not inactive or disabled) when the on disabled callback was fired. The mystery would be why?

gray mural
#

who knows.., I just have this OnDisable method on that GameObject

private void OnDisable()
{
    onOptionSelect -= SelectOption;
}
dusk apex
#

Did whoever reference and disable the script destroy it?

gray mural
dusk apex
#

Who destroyed the object before the callback was made?

#

Something has destroyed it before the callback was made

gray mural
#

the typeSelectionField is disabled a by that time

#

(and destroyed)

dusk apex
#

Figure out why it was destroyed when it shouldn't have been destroyed or don't modify it after it's been destroyed.

dusk apex
#

Then the disabled callback threw the error

gray mural
#

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)

latent latch
#

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

dusk apex
gray mural
latent latch
#

but I dont care if the manager doesnt know about this more derived type or SO

dusk apex
latent latch
#

maybe I'm not understanding the syntax but IDE doesn't seem to help

quartz folio
#

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

latent latch
#

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

quartz folio
#

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

latent latch
#

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

dusk apex
quartz folio
#

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

latent latch
#

Hmm

quartz folio
#

I forget whether this is something you can do with covariant generics

#

that sort of thing just confuses me

latent latch
#

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

dusk apex
#

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.

latent latch
#

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

latent latch
#
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

dusk apex
# latent latch the covariant stuff requires basically duplicating your classes into interfaces ...

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.

latent latch
#

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

dusk apex
#

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)

rain crater
#

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

leaden ice
#

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

rain crater
#

Alright, that makes sense

#

but then, what about the gameobject not being deleted?

leaden ice
#

It will be destroyed at the end of the frame

rain crater
#

but it doesn't, the game keeps running (in a broken state, that is)

leaden ice
#

If you think it's not, maybe You're calling this function on the wrong object

warm aspen
#

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

leaden ice
#

Although it will have been destroyed probably so

#

Yeah

rain crater
#

Yeah, just found out that there actually is another gameobject holding that script, and I was dead sure there's only one thonk
Well, that should fix everything

rain crater
fervent furnace
#

you can run code on a destroyed object since the instructions are stored separated

rain crater
#

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.

fervent furnace
#
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);
}
scarlet viper
#

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

leaden ice
#

they're just references to the same object

fervent furnace
#

reference is a pointer pointing to the memory space, the memory pointed by them will not duplicated

sinful hull
#

Hi all. I want to check for inappropriate images within unity. Is there any sdk available for this?

heady iris
tawny mountain
#

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))
    }
leaden ice
#

if they're different, it's moving

tawny mountain
#

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;
    }
leaden ice
tawny mountain
#

I've debugged in the if/else for the animator as well as in the update function outside of if and else statements

leaden ice
#

ok and what did you log and what did you find when you did that

tawny mountain
#

the else statement doesn't run its debugs

leaden ice
#

so then that's never happening

tawny mountain
#

right

leaden ice
#

keep investigating why

tawny mountain
#

checking if velocity is less then 0.1

leaden ice
#

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; }

tawny mountain
#

on we are returning out of update if it is

leaden ice
#

exactly

#

so the else statement is never going to get a chance to run

tawny mountain
#

And I can't set the animation to idle before I exit , I've tried that

leaden ice
#

wdym

tawny mountain
#
if (Vector3.Distance(trackingPosition, transform.position) < 0.1)
        {
            animator.SetFloat("Walking", 0);
            return;
        }
leaden ice
#

why can't you do that?

tawny mountain
#

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

hard viper
#

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.

scarlet viper
#

anyone knows if theres a difference in performance between instantiating existing gameobject and instantiating a prefab

#

(the first option will clone it)

hard viper
#

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

fervent furnace
#

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

gray mural
#

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 { }
latent latch
#

Yeah, usually if it's more than an ID then you need data containers and a specific load manager for each

gray mural
#

and the same for every item that I've got?

latent latch
#

Hmm, why does enemy derive from ItemBehaviour

dusk apex
latent latch
#

oh yeah probably

gray mural
#

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...

gray mural
dusk apex
sage latch
# gray mural In my game I save items in levels by their name and position. I use name to get ...

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

vernal compass
#

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?

unborn pewter
#

can anyone help me with a problem??

knotty sun
unborn pewter
#

please anyone`??

knotty sun
#

if you want help you need to ask your question first

swift falcon
#

my music volume script working in unity but not when i build it

vernal compass
unborn pewter
#

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?

swift falcon
#

click on package unity registery and put it to built in

unborn pewter
#

ok ill try

swift falcon
#

and after that put it back to unity registery

rigid island
swift falcon
#

how do i do that

rigid island
tawny elkBOT
#
๐Ÿ“ 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

rigid island
#

click link, scroll down

#

Player-related log locations

knotty sun
rigid island
#

althought it might be UI issue

rigid island
unborn pewter
#

it didnt work : (

vernal compass
rigid island
#

by music volume do you mean a slider ? @swift falcon

#

or code wise

swift falcon
#

i mean how can be the ui when i change the slider in unity music stops and in build dosent\

unborn pewter
#

why does the package not sho up for me in the package manager : (

swift falcon
#

idk

rigid island
swift falcon
#

yes

unborn pewter
#

anyone know what could be the problem??

#

my package manager does not have all the packages

swift falcon
#

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

gray mural
rigid island
#

in build

knotty sun
#

@unborn pewter it might help if you
A) Told us which package you are looking for
B) Post a screenshot of your Package Manager

rigid island
unborn pewter
#

ohhh i founf it out. i need a new version of unity

gray mural
unborn pewter
#

why does it say i have 0 bytes when i have like 200

#

i cant installa newer version of unity : (

rigid island
unborn pewter
#

how can i do that

#

can i call you and screenshare. maybe that will be easier??

scarlet viper
#

is there a way to get GetComponentsInChildren without parent transform included ?

unborn pewter
#

idk why but for me just more and more problems pop up : (

#

and idk how to fix any of it

rigid island
unborn pewter
latent latch
#

actually I forget now

sage latch
gray mural
unborn pewter
gray mural
unborn pewter
#

oh wait.. fo course another f"#ing problem!!

#

noooooooo

#

idk guys. it just seems like nothing works

rigid island
#

is just windows that sucks xD probably

rigid island
unborn pewter
#

wait i did somthing... and it seems to be working

swift falcon
#

@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."

unborn pewter
#

: )

#

finnally

#

bro ur a real time saver thank you so much ๐Ÿ˜ฎ

rigid island
rigid island
swift falcon
#

the Palyer olg from the appdata local low

rigid island
# swift falcon

after running the game right?
hmm can you share the music script thing

#
  • show setup
swift falcon
#

is working in unity bot not when i build it

rigid island
#

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

hard viper
#

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 -.-

fervent furnace
#

-1==0xffffffff

#

(you may see memset(memo,-1,size) on dp problem because of this)

hard viper
#

why is the rightmost bit of -1 not 0?

fervent furnace
#

~1+1

hard viper
#

I thought the rule is: leftmost bit is 0 if positive. If leftmost is 1, all other bits are complement

fervent furnace
#

~1 you get 0xffff fffe and +1

#

then 0xffff ffff

#

two complement

hard viper
#

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?

fervent furnace
#

there is still a sign bit, you can check it by >>31

#

INT_MAX is 0x7fff ffff and the leftmost bit is zero

hard viper
#

iโ€™m still confused then as to why -1 = ~0

fervent furnace
#

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

solemn raven
#

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;

fervent furnace
#

TextAsset

solemn raven
hard viper
#

so youโ€™re saying:
-x = ~x + 1.
x >> 31 = sign bit.

fervent furnace
#

yes

hard viper
#

ty tina. itโ€™s hard to find good info online because lots of sources conflict because they start talking about different representations

fervent furnace
#

two complement system

hard viper
#

one more question if I can: I get (-1) >> 31 = -1. Is this because >> isnโ€™t working on the raw binary?

fervent furnace
#

oh it may be arithemetic right shift

hard viper
#

follow up then; Why wouldnโ€™t that be zero?

fervent furnace
#

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

hard viper
#

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?

fervent furnace
#

no they just shift the bit but arithmetic is:
0b????.... fill the ? with the original leftmost sign while logical is filling it with 0

hard viper
#

ty for your time btw tina. this helps a lot

fervent furnace
#

and whether >> is logical is arithmetic is depend on data type unsigned is logical signed is arithmetic
also depends on the language....

frigid bone
#

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.

main shuttle
frigid bone
#

Is there a path to set as the active path from that request?

main shuttle
#

You can catch that it failed to get a path to the player, and set another path to dig yeah.

quaint reef
#

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?

hard viper
#

i think the solution to my negative numberproblem is to avoid all bitshift operations on negative numbers lol.

knotty sun
fervent furnace
#
    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
knotty sun
#

I think you mean PostProcessVolume

fervent furnace
#

idk will it depends on compiler

static bramble
#

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

hard viper
#

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?

main shuttle
orchid bane
#

Does GetComponents return components in the same order as the one they are in in the inspector?

knotty sun
#

not necessarily so dont rely on it

orchid bane
#

2018.4 docs say it's reliable but the new ones dont

#

@knotty sun

knotty sun
orchid bane
dawn pier
#

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?

bold pawn
#

[Serializable] == [System.Serializable]?

ionic adder
knotty sun
heady iris
#

in general, using allows you to omit the namespace

#
using Foo.Bar.Baz;

Foo.Bar.Baz.Buz
Buz
#

both would work

swift falcon
#

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);
}

}

celest iron
#

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.

bold pawn
#

You should probably post the whole script...

celest iron
#

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

tawny elkBOT
#
Posting 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.

celest iron
#

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?

#

๐Ÿ‘

cinder ore
#

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;
ย  ย  }
}
atomic sinew
#

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.

plush ridge
#

You also don't have to put the decimal. You could do -10f, 0f, and 10f. Either way is fine, but just a tip.

hidden lance
#

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.

leaden ice
placid island
#

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

leaden ice
placid island
leaden ice
#

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

placid island
#

I mean the path here. It now shows the former path.

leaden ice
#

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?

placid island
#

No, the namespace is correct

leaden ice
#

Probably just needs to be recompiled

#

Burst recompiled maybe

placid island
#

Oh, wait. I just deleted all the .meta files and reloaded the project. Won't it recompile every script?

leaden ice
#

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)

placid island
placid island
dawn pier
tame spruce
leaden ice
#

Because that doesn't really seem correct

tame spruce
#

Agreed

scarlet viper
#

Are there any cool ways for creating a prefab, passing a variable and calling a method on it?

  1. I have:
Instantiate(prefab).getcomponent<script>().Create(parameter);
  1. 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

fervent furnace
#

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

latent latch
#

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

outer brook
#

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

pastel cosmos
#

Did u make sure your scenes are imported

#

And u used the right indexes

#

Or maybe you loaded them with they're name

outer brook
pastel cosmos
#

Yea

#

I mean when u exported it

outer brook
gray mural
#

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. ( - - - - )

main shuttle
main shuttle
gray mural
#

I see, do this lines have a fixed size?

main shuttle
#

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 UnityChanLOL

gray mural
main shuttle
gray mural
main shuttle
#

But atleast you have the term you are probably looking for.

main shuttle
#

Outline shaders, there are wholes swathes of 3d and 2d tutorials on this.

gray mural
umbral radish
#

I am going back to Unity again

gray mural
#

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);
    }
}
knotty sun
gray mural
tulip cosmos
#

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:

  1. 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.

  2. 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) ?

leaden ice
#

Yes 2 is basically the standard way to do UI

#

It's called the observer pattern

tulip cosmos
#

Oh nice

#

I'm gonna look into that, thanks

steady moat
# tulip cosmos Hello, I have 2 questions. Here's the context: when switching weapon, the weapon...

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.

vivid remnant
#

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().

#

Could somebody help me understand why using Rigidbody.MovePosition() instead of Transform.position is causing the force applied on the interactable objects appear greater?

steady moat
vivid remnant
#

The projectiles have kinematic rigid bodies so I can't apply forces on them or change their velocity.

steady moat
#

Also, rigidbody.MovePosition should be use in FixedUpdate

vivid remnant
#

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.

vivid remnant
#

True but do you think this is what's causing the behavior?

vivid remnant
steady moat
steady moat
leaden ice
#

No need to be doing something every frame for every projectile

leaden ice
#

Make them dynamic

vivid remnant
#

You mean non-kinematic?

leaden ice
#

Yes

#

The opposite of kinematic is dynamic

vivid remnant
#

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?

leaden ice
#

It will let you delete 90% of your code, improve performance, and give you better behavior.

vivid remnant
#

Oh, no, I get that. I meant to ask why does using a kinematic rigid body cause this behavior to occur.

latent latch
#

!learn

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ 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/

leaden ice
#

So of course it doesn't collide

unborn pewter
#

can anyone help me with something??

vivid remnant
#

You can just ask directly. ๐Ÿ˜„

unborn pewter
#

i can not drag my player in here

#

do you know the problem??

#

ive been stuck on this for like 1hour

leaden ice
#

Which is what your field wants

unborn pewter
#

?

#

um ill try

leaden ice
#

You'll try what

unborn pewter
#

idk

leaden ice
#

What are you doing here

#

Why do you have a list of network prefab lists

unborn pewter
#

um can i screen share in a vc then you can help??

leaden ice
#

No

unborn pewter
#

ok

leaden ice
#

Just explain in English what you're trying to accomplish

unborn pewter
#

im trying to make a multiplayer game. and to spawn in my player i need to put my player in this prefab list

leaden ice
#

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

unborn pewter
#

ok

#

but darging it into the thing worked on the vid??

leaden ice
#

Didn't you already drag it here

#

In the player prefab slot

unborn pewter
#

yea, but acording to the vid i need to drag into the network prefabs list

leaden ice
#

Go back

unborn pewter
#

but i can try it without

leaden ice
#

You probably missed something

#

Or are doing something wrong

unborn pewter
#

ok

leaden ice
#

Generally the type of the object has to match the field it's being dragged into

unborn pewter
#

ill try double checking the vid

#

i tried whatching the vid again but it still doesn't work

leaden ice
#

Without further context it's not really something I can help with

unborn pewter
#

yeah i get that

#

thank you for trying to help : )

leaden ice
#

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

unborn pewter
#

it does have the network object script on it tho

leaden ice
#

Doesn't help us

#

If we need a banana, it doesn't help if we have an apple

unborn pewter
#

true

leaden ice
#

It's also possible the tutorial you are following is using a different version of the network framework or something

unborn pewter
#

yeah

#

it is using a diffrent version of unity

#

mby that is why??

leaden ice
#

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

unborn pewter
#

ill try to find a newer tutorial then

#

thanks for your help

swift falcon
#

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?

knotty sun
swift falcon
#

Oh yea I just noticed

tulip cosmos
hard viper
#

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?

gray mural
#

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

rigid island
#

or just making that shape

gray mural
#

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)"

rigid island
#

yeah this is some maths beyond my understanding :\ soz

#

dynamic shapes n all that

gray mural
#

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

vivid remnant
steady moat
vivid remnant
#

I changed that, meanwhile.

#

Look

steady moat
#

You only need to set velocity once

vivid remnant
#

Ignore the message in Debug.Log(). I'm tired. :)))

steady moat
#

Also, you can use OnTriggerEnter/OnCollisionEnter for collision

vivid remnant
#

I'm doing that already.

steady moat
#

Then why raycast

meager iris
#

any1 know why this doesnt wokr

vivid remnant
# steady moat Then why raycast

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?

rigid island
steady moat
vivid remnant
#

If by that you mean I should set the Interpolation of the rigid body to Interpolate, I did that already.

rigid island
# gray mural Hello, does somebody know what I should use to do this kind of selection in Unit...

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

vivid remnant
gray mural
steady moat
gray mural
vivid remnant
#

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.

rigid island
scarlet viper
#

oh sorry

vivid remnant
#

@steady moat, thank you so much! ๐Ÿค

meager iris
#

how do i keep music playing whie changing scenes

rocky jackal
#

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) ?

simple egret
rocky jackal
#

Okay

near wagon
#

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

#

its at line 53

#

like the function

#

oh and i didnt mention its 2d

mellow sigil
#

You override horizontal velocity in FixedUpdate so the knockback gets undone there

mellow sigil
#

Don't set velocity directly to move. Use AddForce.

near wagon
#

oh wait is it the forcemode thing

#

oh uhh

mellow sigil
#

The default force mode is correct. You'll have to adjust the amount of force, drag and friction until it feels right

spring creek
# near wagon how can i fix it

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

near wagon
#

ok thx

gray mural
rigid island
#

or GL potentially

opaque falcon
#

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/

terse garnet
#

Guys, I want to use this code snippet but I can't add the JavaScriptSerializer from which library does it belong to?

hard viper
#

are there any watchouts I should know about with respect to structs and interfaces?

simple egret
#

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

terse garnet
simple egret
#

That thing is deprecated, use a JSON serializer that can support root collections types such as Newtonsoft.Json

rigid island
#

!code

tawny elkBOT
#
Posting 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.

proven path
#

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?

simple egret
#

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.

rigid island
#

everything should be private for the most part but yeah stick to properties if you need to grant access outside

fervent furnace
#

i just stick to public, if none or lazy evaluation on that variable is required

proven path
gray mural
elfin tree
#

What is the code equivalent of doing this at runtime? (alt+shift pressed)

latent latch
#

Get max screen space on the x then shift pivot to it?

elfin tree
latent latch
#

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

vocal harbor
#

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?

sly iron
#

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

sly iron
#

and script removed from compnonets

#

I try to add it again but it still removed

somber nacelle
#

are you perhaps destroying the component in Start or Awake?

vocal harbor
#

it's in fixedUpdate btw

somber nacelle
#

is the rigidbody kinematic?

vocal harbor
#

my cubes dont have rigidbodies cus then they just ignore every collisions idk why

somber nacelle
# vocal harbor

joueurRB.MoveRotation(targetRotation); shouldn't work if you've frozen the rotation. so you're probably rotating it via the transform somewhere

vocal harbor
#

huh

#

i double checked and im not rotating anywhere else

simple egret
#

It cannot rotate because you checked these three:

vocal harbor
#

so why am i rotating lol

#

this is driving me insane

simple egret
#

Because something uses the Transform to rotate other than the rigidbody

#

Or a parent/child object rotates

vocal harbor
#

well my cubes dont have any script to move, they all just follow the player's movement

rigid island
vocal harbor
#

i must be missing somehting

rigid island
#

is that what ur asking

vocal harbor
#

they are basically just additional colliders for the player

fervent furnace
#

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

stark sun
#

when I drop enemy once it never follows me back only ascends to air and rotate randomly

sly iron
#

I find some problems is unity consle

somber nacelle
#

!code ๐Ÿ‘‡

tawny elkBOT
#
Posting 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.

sly iron
#

NullReferenceException: Object reference not set to an instance of an object
cup.Update () (at Assets/cup.cs:19)

@somber nacelle

somber nacelle
#

show the contents of cup.cs

sly iron
#

can I send it here?

rigid island
sly iron
#

just short code

somber nacelle
#

you never assign to rb. also for future reference, always start debugging with the first error in your console. not the last

fervent furnace
#

and your code hiding the gameObject property inherits from monobehaviour

rigid island
#

it phase thru stuff

vocal harbor
#

is there some way that i could make it work?

rigid island
#

just tested it

vocal harbor
#

yeah at low speed it's fine but when turning at the speed that i want it goes throught the walls

sly iron
#

@somber nacelle@fervent furnace thank you

#

I just forgot to write public

#

new in C#

rigid island
sly iron
vocal harbor
#

also rn im debugging code that my friend wrote so im kinda lost in his things

rigid island
stark sun
#

can someone take a look at my thread

wanton sierra
#

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

spring creek
#

transform.position += ?

#

Or something else?

wanton sierra
#

charactercontroller.move

spring creek
#

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?

wanton sierra
#

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

spring creek
#

Well GetAxis has smoothing already, so I guess suggesting that won't help haha.

I do see you call cC.Move twice though

wanton sierra
#

yes one is for gravity, one for movement

spring creek
#

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

green anvil
#

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
wanton sierra
#

well

#

not the brackeys issue

#

but

#

Had to uncheck "snap" in the project settings

spring creek
spring creek
green anvil
#

yes i just doesnt move down

spring creek
green anvil
#

k

#

doing it now

tulip cosmos
# leaden ice Yes 2 is basically the standard way to do UI

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 ?

steady moat
leaden ice
#

Anyway there's no significant performance difference between an event and a normal method call

steady moat
safe ore
#

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);
    }
tulip cosmos
safe ore
safe ore
#

have an enemy FOV, so if the enemy can see within the Frustum the player will be spotted

steady moat
safe ore
#

What do you mean?

steady moat
safe ore
#

With Ray casts?