#archived-code-general

1 messages ยท Page 401 of 1

sullen drift
#

might came out

pliant rivet
#

okay

#

did you use any learning resources?

fleet gorge
#

literally just make games and publish them

#

these things are remembered through practice

pliant rivet
fleet gorge
#

then you're more than prepared

sullen drift
#

sometimes. all the answers are right, but 1 answer is the most efficient and optimize

pliant rivet
#

i see

fleet gorge
#

they test a bit of version control

pliant rivet
#

they ask about unity services?

fleet gorge
#

that's for the other cert, unity developer

#

which in addition to everything above also tests on unity cloud, deployment and other services

#

not as many coding qns

pliant rivet
#

got it. they will test on 2022 lts right?

fleet gorge
#

that I'm not sure

pliant rivet
#

okay

fleet gorge
#

even if they do you'll figure it out

pliant rivet
#

thanks guys you have been a real help to me :>

fleet gorge
#

๐ŸŽŠ good luck for your test

#

Are you doing this for yourself or is your organisation sponsoring you?

fleet gorge
#

Ah I see

#

I'm just gonna say that employers won't care about the cert that much, they care more about what you already have out there

pliant rivet
#

i am actually in third year - college rn and i have a semester break so i planned to give the exam

pliant rivet
#

i am also learning unreal side by side

dense swan
#
    void Start()
    {
  #if UNITY_RELEASE
        // Only destroy FpsCounter in release builds.
        Destroy(gameObject);
  #endif
    }

I'm trying to run script only on release builds. but this doesn't seem to work. Maybe I don't understand what 'release' even mean for unity.
How do I run script only if I ran the game from editor OR from build with "Development Build" checked?

simple egret
#

Not Editor nor development build should be a #if !UNITY_EDITOR && !DEVELOPMENT_BUILD

wary veldt
#

Why is there no stacktrace for some errors?
For example, now I have error
Can't destroy Transform component of 'Button'. If you want to destroy the game object, please call 'Destroy' on the game object instead. Destroying the transform component is not allowed.
I know that I can simply inspect all of the Destroy calls, but in a big project it would be a real problem
Is there a way to get the exact line problem occurs?

dense swan
steady bobcat
thin aurora
#

You can most likely click the error here to open up the gameobject related to this.

thin aurora
#

That's shitty Unity debugging for you

#

It's very unclear

wary veldt
#

That's really strange to let you destroy transform as well, just to send an error each time you actually do this

hexed pecan
#

It doesn't destroy the transform

#

A transform is always needed on a gameobject

#

Weird that it the error does not have any context though. Maybe the object is already destroyed by something else ๐Ÿค”

wary veldt
wary veldt
hexed pecan
#

Yep!

mossy shard
#

In a grid, how would i find the closest node to a world position without iterating trough each node and calculating the distance between the current node and the world position (inefficient)

hexed pecan
#

I actually just wrote something like that...```cs

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private Vector3Int WorldToCellCoord(Vector3 worldPos)
    {
        worldPos /= gridSize;
        return new Vector3Int(Mathf.FloorToInt(worldPos.x), Mathf.FloorToInt(worldPos.y), Mathf.FloorToInt(worldPos.z));
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private Vector3 CellToWorldCoord(Vector3Int cellCoord)
    {
        return new Vector3(cellCoord.x * gridSize, cellCoord.y * gridSize, cellCoord.z * gridSize);
    }```
#

This one does not have offset

mossy shard
#

oh

#

thank uuu

tawny spoke
#

so like. Got an existing project, has 1 sln and 6 csproj files. its meant to produce a few dlls with specific guids, to serve as 'stubs' against the vrchat sdk package. I wish to extend it with some additional data types added in later sdk versions. I can open it in jetbrains rider and do code editing/etc, but it doesn't have reference to any of the unity dlls. if I put the existing project into a unity project and open it it ends up destroying the dll separation and bundles them all into one. Am I missing something here?

#

(for reference: linux)

visual fjord
#

Question general
If I use C# events for a differences systems, Could I do that a gameobject(1) shoot an event to other gameobject(2), this could shoot an event to gameobject(1)?

#

It's right?

leaden ice
#

Your scripts can do whatever you want

compact spire
#

Hey everyone, been struggling at this one for a bit. I'm trying to create a grid based placement system for different shaped blocks. If I use a cube collider on each one that fits the cells of the grid, how do I resolve which "side" is being looked at when attempting to place one block on another. I guess this simplifies to, how do I determine which side of a cube collider is being hit when it's hit by a ray?

leaden ice
compact spire
#

Interesting

#

I think that's enough for me to go on, thanks @leaden ice

#

sweet that worked

wheat spruce
#

Why is my Spline instance persisting even after I stop running the game in the editor?

  public class ZenComponent : MonoBehaviour
  {
    public static Spline PerimeterSpline;
    // Spline sets the perimeter of the garden environment

    private void Awake()
    {
      PerimeterSpline = new Spline();
    }

    private void OnDestroy()
    {
      PerimeterSpline = null;
    }

    private void OnApplicationQuit()
    {
      PerimeterSpline = null;
    }
  }```
heady iris
#

this doesn't have an [ExecuteAlways] attribute on it, does it?

wheat spruce
#

I have a class that uses the spline to instance those box colliders. When the spline first gets created, that box-collider class doesnt construct because at that moment, the Spline hasnt been fully constructed. Stopping the scene and restarting it, the colliders do get built because at that point, the spline is pre-existing

heady iris
#

and do you have Domain Reload disabled?

wheat spruce
heady iris
wheat spruce
#

and no, theres no attributes on anything

heady iris
#

Can you show the code that's constructing the box colliders?

wheat spruce
#
  public class SplineComponent : MonoBehaviour
  {
    public HandleComponent HandlePrefab;
    private List<HandleComponent> _handles;

    private Spline _spline => ZenComponent.PerimeterSpline;    //SplineComponent was what construct the spline before

    private void Update()
    {
      if(_spline == null)
      {
        return;
      }

      if(_handles == null)
      {
        CreateHandles();

        void CreateHandles()
        {
          _handles = new();
          foreach(var point in _spline.Polygon.Points)
          {
            var handle = Instantiate(HandlePrefab, point.ToVec3(), Quaternion.identity, transform);
            _handles.Add(handle);
          }
        }
      }

      for(int i = 0; i < _handles.Count; i++)
      {
        _spline.SetPoint(i, _handles[i].transform.position.ToVec2());
      }
    }
  }```
heady iris
#

The SplineComponent sets the spline points after it tries to create the handles, so I would expect this to never work correctly.

#

given the "ZenComponent" name -- is Zenject involved here?

wheat spruce
#

SetPoint? apologies, its a badly named thing. Its actually SetPointPosition

#

just uses the handles position to drive each point on the spline

heady iris
#

it's using the spline's points to create handles, and then using those handles to set the spline's points..?

visual fjord
heady iris
#

it's a bit self-referential

wheat spruce
heady iris
#

Oh, this has nothing to do with the Splines package, okay

#

that's where the shape comes from

wheat spruce
heady iris
#

I would check if OnDestroy or OnApplicationQuit are actually being executed

#

(along with Awake)

wheat spruce
heady iris
#

Is this consistent across every Play Mode entrance and exit?

wheat spruce
#

if I make any changes to the code, it does clear the instance

heady iris
#

Notably, with Domain Reload off, you may see differences on the first Play Mode entrance after a recompile

wheat spruce
#

the video was shown directly after I saved the C#

heady iris
#

(since a domain reload does happen at that point)

wheat spruce
#

it does that the first time, then every other time I enter play the handles get created

heady iris
#

hang on, I have a really dumb idea

#

this doesn't make any sense because the Spline type is non-serializable and it's in a static field

wheat spruce
#

thats interesting. changed the setting to this, and even after I make changes to the code, it always creates the handles without issue

heady iris
#

but can you slap [System.NonSerialized] on that static field anyway

heady iris
wheat spruce
#

same

heady iris
#

well, actually

#

it's consistent if my crackpot theory is true

wheat spruce
#

[System.NonSerialized] creates handles fine too

heady iris
#

so with domain reload disabled and that attribute on the Spline field, you get the correct behavior every time?

heady iris
#

and if you remove the attribute, the handles don't get created on the first play mode entrance after a recompile?

leaden ice
#

If it does what you want it's correct

wheat spruce
#

which makes no sense because if the spline was always being created before the handles get a chance to read the spline, then surely if NonSerialized means what I'd expect, the handles should never be created correctly

heady iris
heady iris
#

Unity will serialize fields that you haven't actually told it to serialize

#

for example, private fields

#

It does this so that you can see them in the inspector's debug view

#

I had a problem once where it was putting garbage into an InputAction field

#

so instead of a null, it was some weird default

#

I fixed that by explicitly telling Unity to not serialize the field

#

But this situation is different for quite a few reasons

#

your Spline class isn't serializable at all and that field is static

#

And even if Unity was somehow trying to serialize the field, it would run the default constructor of Spline, which would populate it correctly

#

I'm guessing the handles aren't appearing on the first run because the spline has zero points in it

#

Is PolyShape serializable?

visual fjord
wheat spruce
#

let me put everything back to when the handles didnt get created the first time, I want to step through and see whats happening

heady iris
#

Log the number of points in the spline's polygon when you try using it in SplineComponent. You should see a zero when the handles fail to appear

#

But that also doesn't make sense, because the Awake method in the ZenComponent should run first

wheat spruce
#

ooohhhh

#

noticed it skips past this on the first ever run (when the handles dont get created correctly until the next playmode)

#

then on the second run, somehow they begin as null

heady iris
#

the Awake method on ZenComponent is running first, isn't it?

wheat spruce
#

let me check

heady iris
#

or is ZenComponent spawning in a bit late?

#

It feels like you have something that runs outside of Play Mode that's putting a bogus value into that field

wheat spruce
#

SplineComponent calls first

#

I think?

heady iris
#

right, but SplineComponent is doing its work in Update

heady iris
#

I don't see any way for a value to sneak in there

wheat spruce
heady iris
#

AFAIK Unity doesn't serialize static fields under any circumstances

#

but given that the NonSerialized attribute had an effect, hm...

wheat spruce
#

basically all these parts are in several classes, now that theyre all working, the refactor will tidy stuff up

heady iris
wheat spruce
warm rover
#

Is there anyway to convert a obj to a navmeshsurface

wheat spruce
#

honestly, I might go back to SplineComponent being the thing that constructs the Spline, not the ZenComponent

heady iris
wheat spruce
#

probably was silly to have Zen construct the Spline

heady iris
wheat spruce
#

all seems good now!

public class SplineComponent : MonoBehaviour
{
public HandleComponent HandlePrefab;
private List<HandleComponent> _handles;

public static Spline PerimeterSpline;
public Spline GetSpline() => PerimeterSpline;

private void Awake()
{
  _handles = new();
  PerimeterSpline = new Spline();
}

private void OnDestroy()
{
  PerimeterSpline = null;
}

private void OnApplicationQuit()
{
  PerimeterSpline = null;
}```Now the spline is definitely being erased after the scene stops, and the handles get created without any issue
rugged pond
#

Hello, can someone give a tip how to check if i click on another inventory slot to change active one and if i dont do it to execute another part of code?

Here is what i already have

private void Update()
{
    if (InputUtilities.PressButton("Use") && isActive)
    {
        // try to change slot

        // otherwise use item from current slot
        UseItem();
    }
}

---

public void OnPointerClick(PointerEventData eventData)
{
    if (eventData.button == PointerEventData.InputButton.Left)
    {
        OnLeftClick();
    }
}


public void OnLeftClick()
{
    inventoryManager.DeselectAllSlots();
    selectedSlot.SetActive(true);
    isActive = true;
}
wheat spruce
#

@heady iris what do you think the problem might have been? the behaviour it was doing before seemed really bizzare

heady iris
#

There was clearly an invalid Spline object stored in that static field after recompilation

#

I just don't see any reason for it to be there

#

If the type was serializable and the field wasn't static, it would be plausible

#

(because I've had problems with that before)

wheat spruce
#

what worries me is I would never have spotted the problem until I happened to get the code to clear the static object

heady iris
#

yes, it was quite vexing when I had a similar issue

#

mysterious bogus object

wheat spruce
#

oh god, this might have explained some issue before where no matter what, something wasnt initialising correctly

heady iris
#

I can't get that exact behavior to happen

#
    public class Foo
    {
        public List<int> contents;
        
        public Foo()
        {
            contents = new List<int>();
            contents.Add(1);
            contents.Add(2);
            contents.Add(3);
        }
    }

I have a static Foo field on another class, and I check if it's null or not and log its contents

wheat spruce
#

I guess stopping this from happening is the msot important thing

heady iris
#

i also construct an instance in Update if it's null

#

It's always either null (during the first play session) or valid with three items in the list (during subsequent play sessions)

#

I guess I should exactly recreate it, by creating a new monobehaviour with the static field on it

warm rover
#

sorry for the late reply

wheat spruce
#

Surely as long as you can click the inventory slot to select it, the same logic will apply no matter which one is clicked

heady iris
#

That way, you can switch it to "Current Object Hierarchy" mode. That will keep it from trying to use other random things in your scene

rugged pond
warm rover
#

like i need the obj converted to the navmeshsurface

heady iris
#

I have no idea what "converted to the navmeshsurface" means

#

Are you trying to let an agent walk around on a moving platform, maybe?

#

Explain what your actual goal is, not your attempted solution

warm rover
#

i need to set the navmeshdata

heady iris
#

Are you trying to update an existing navmesh after moving things around at runtime?

wheat spruce
# rugged pond I can click on inventory slot to change it but problem is if i have a consumable...

I'm not quite sure, ive got little experience when it comes to inventory type things.
What I would suggest doing is try and get the type of logic you want, but do the testing just with code, not actually using the inventory objects.

Say you had an list with 4 strings, pretend the list is the same as your inventory collection. Press keys 1-4 to set which item is "selected" and then press space to simulate you consuming it to remove it from the list

warm rover
heady iris
warm rover
heady iris
#

so that you can navigate around a level you generated at runtime, instead of something you built in the editor

warm rover
#

like the surfaces

wheat spruce
#

if you can get that example code behaving exactly how you would in the inventory, you can substitute the list with the collection of items, and then get the code to do the same thing but with the actual game items

heady iris
rugged pond
wheat spruce
# rugged pond I see where its going but problem is i use same button (mouse0) to use item and ...

What I mean is clicking on a UI item to set the selection, has a similar principle to "press number 2 to find the second string in a list", its a little more abstract to think about, but its a far simpler context to work in. That simplicity will make it a bit easier to work with, as theres not much that could go wrong with just if keycode(2) { selelect item 2 }. Wheras with clicking the UI element a lot more has a chance for error, making it harder to do the primary goal

wheat spruce
#

then later on, rather than pressing a key for 2, swap that out with clicking on the second UI item and tell the rest of the code what one was pressed. It will then still do the same "find the second string in the list" but now youve got part of your intended code working in that simpler code

rugged pond
# leaden ice Can't you just do an if/else

I've tried to add if (!change slot) before calling UseItem() but then every time i click somewhere out of inventory it would just not work. Probably bc of broken logic in 'change slot' function so i will invest in it too

rugged pond
leaden ice
rugged pond
#

This would use item at first and if slot is empty it will change it while i want something like if i clicking on non-active slot then this slot become active w/o using item and if i click somewhere out of inventory it just use item from current slot

bleak olive
#

I'm trying to have a functioning multiplayer, but everything I've done to work with this template I'm using has just further screwed it up, I think I might just need to restart and figure it out from scratch

#

I've never done multiplayer and multiplayer in Godot was always a big no no

latent latch
#

godot eNet is pretty straight forward. I think fishnet docs are pretty weak considering

#

but fishnet does some have some features like network prediction/extrapolation

jovial barn
#

I'm having a bit of a design problem. I have 3 singletons: wave system, enemy tracker, and waypoint system.

I'm trying to get over my habit of making all my singletons directly dependent on each other but I'm not sure how else to make this structure work. is there a way to make this work with scriptableobjects or some other thing that gets rid of the need for direct dependencies?

#

I feel like I got a decent start with using events but they still have a one-way dependency that goes in circles, so each system still requires every other system to work

latent latch
hexed pecan
bleak olive
inner wasp
#

I'm having a bit of trouble drawing a Inventory items icon ontop of the inventory grid slot it's supposed to be drawn on. I'm pretty sure it has to do with the layout not being rebuilt but I'm having trouble getting it to behave the way I want. The issue I'm running into is the position of the InventorySlots don't appear to have been set after the LayoutRebuilder is called. When I step through it I can see that each InventorySlot has the same position.

When an inventory is drawn I have a GridLayout I instantiate a bunch of InventorySlots into,

            // Up here I'm instantiating a bunch of InventorySlot UI elements

            // Force the layout to update so we can rely on the cels being placed accurately.
            LayoutRebuilder.ForceRebuildLayoutImmediate(gridLayout.GetComponent<RectTransform>());

            //After the LayoutRebuilder is called I reference the position of those InventorySlot's to place the ItemIcons properly.
            
#

Everything is happening within one update, it makes sense that the GridLayout woudln't have time to update.

vagrant blade
#

There's no off topic on this server.

leaden ice
#

just make sure the inventory slot prefabs have the correct anchoring and that you instantiate them with the form of Instantiate that accepts a Transform parent

inner wasp
#

I shouldn't need to force a layout update even if I'm adding a bunch of items to a grid layout and then in the same update trying to reference their position?

leaden ice
#

I guess perhaps if you're trying to reference their positions immediately. What are you using that for?

dapper pewter
#

Anyone know why canceling doesn't work here when rebinding controls? RebindCancelled is never called, it calls RebindComplete when I press Escape.

inner wasp
#

I essentially have two layers to my inventory. A background of "InventorySlots" and a foreground of "ItemIcons" I want drawn ontop of them. I'm using the position of the InventorySlot to decide where to place the ItemIcons on the screen when the UI is drawn.

leaden ice
inner wasp
#

In my case I don't know what Inventory is going to be drawn until something like a chest is opened. Since I don't know what inventory is going to be drawn I don't know how large my inventory grid needs to be, I have to draw that all at once.

leaden ice
inner wasp
#

I run into issues with the rendering order. The next slot in line will render overtop of the ItemIcon since it's higher in the rendering order. If you change the rendering order your InventorySlot will be rendered at the end of the GridLayout instead of at it's correct position.

#

I guess that points to a bigger architectural issue with what I'm doing.

dapper pewter
leaden ice
#

I suspect you can call WithCancellingThrough multiple times?

#

Not sure

dapper pewter
#

According to the docs it can only be called once

dapper pewter
#

Still wouldn't allow rebinding B button. I might have to not allow cancelling for now

leaden ice
#

Not allowing canceling is probably what I would do ๐Ÿค”

#

because then you can never bind whatever the cancel button is

dapper pewter
#

Or maybe "Menu" control

leaden ice
#

you can always just bind it back to what it was previously

#

and you can always make a separate "reset" button for each control that sets it to the default

#

and/or for the controls overall

inner wasp
#

What Praetor is suggesting is pretty common practice.

dapper pewter
#

Looks like "Esc" is not considered to be the keyboard's "Menu" button so */{Menu} does not work

dapper pewter
#

The workaround:

flint plume
#

im running this 3 times at once every few seconds and itll drop to 50fps, how can i optimise it so it doesnt lag or am i fucked

for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                float xCoord = ((float)x / width) * scale + OffsetY * 0.01f;
                float yCoord = ((float)y / height) * scale + normalizedSeed;

                float heightValue = Mathf.PerlinNoise(xCoord * 1, yCoord * 1);// * 0.5f
                //+ Mathf.PerlinNoise(xCoord * 2, yCoord * 2) * 0.25f 
                //+ Mathf.PerlinNoise(xCoord * 4, yCoord * 4) * 0.125f 
                //+ Mathf.PerlinNoise(xCoord * 8, yCoord * 8) * 0.0625f 
                //+ Mathf.PerlinNoise(xCoord * 16, yCoord * 16) * 0.03125f;

                if (!skip)
                {
                    if (x >= gapStart - falloffArea && x <= gapEnd + falloffArea)
                    {
                        float distanceFromEdge = 0f;
                        if (x < gapStart)
                        {
                            distanceFromEdge = 1f - Mathf.Clamp01((gapStart - x) / (float)falloffArea);
                        }
                        else if (x > gapEnd)
                        {
                            distanceFromEdge = 1f - Mathf.Clamp01((x - gapEnd) / (float)falloffArea);
                        }
                        else
                        {
                            distanceFromEdge = 1f;
                        }

                        heightValue = Mathf.Lerp(heightValue, Mathf.Abs(target - heightValue * 0.05f), distanceFromEdge);
                    }
                }
                heightMap[x, y] = heightValue;
            }
        }
jovial barn
#

just so there's a master list of all the enemies

leaden ice
untold nebula
rotund perch
#

How do I make properties appear/disappear depending on what Update Type is set to?

#

after further research this is probably a code-advanced question

#

it's complicated stuff but pretty cool

latent latch
#

Custom inspector stuff

rotund perch
#

It looks like it's free, what do you mean buy?

dusk apex
#

Naughty attributes is free. Odin is not.

rotund perch
#

Oh

dusk apex
#

There was an or.

rotund perch
#

Yeah the first one was for custom inspector stuff which is a unity thing

#

Pretty sure at least

rotund perch
hexed pecan
#

You can make a method that checks if those objects are the same and returns a bool, and use that with ShowIf

#

Or are you asking something else?

rotund perch
#

I'm not sure that would work outside a function

#

it's for NaughtyAttributes like @latent latch had sent

#

yknow what this is way too many resources being put into a script I'll likely use like 5 times

knotty sun
rotund perch
#

yeah...

compact spire
#

If I have a game with an in-game editor, like stormworks/from the depths/Kerbal space program ect... When I'm putting together the craft, there is a lot more editor specific data (connection points, ui elements ect) that aren't part of the "in game" objects. It doesn't make sense to include them as that's adding quite a bit of unnecessary overhead per object, but it also doesn't make a whole lot of sense for them to be completely seperate as the editor needs a lot of the game data. Would it work to make the editor object a wrapper around the game object? Or use something like a scriptable object to store the data for both? I don't think sharing a common interface or using partials/abstracts is the answer... but I am not certain.

rotund perch
#

got a bunch of other unnecessary logic in there too

knotty sun
tawny elkBOT
rotund perch
#

oh thanks

compact spire
#

That solution seems a bit line heavy

rotund perch
#

I've been brainstorming other ideas

#

Maybe having a class that contains all of the other ones so I can just have one array of all of those

#

using enums or something

#

but that has the downside of likely making my levels bigger

compact spire
#

I think scriptableObjects might be the key, but it's been a while since I've tinkered with those

dense yoke
#

When it comes to shooting a gun at another player what is better to use as an example a player shoots an arrow at another player? My question is what is better to start or upgrade so that the arrow hits the target which would be the player?

knotty sun
dense yoke
#

ok

#

Yes and I don't want to make projectiles that respect physics and others that don't.

knotty sun
#

that statement makes no sense and does not answer the question

dense yoke
#

I don't know how to develop the question in Englishnotlikethis

knotty sun
#

you asked about shooting an arrow, there are 3 ways to do this

  1. using physics
  2. not using physics
  3. using animation
    which do you want?
dense yoke
#

one

knotty sun
#

so you need an example of firing a projectile using rigidbody physics

#

what the projectile is is completely irrelevant

dense yoke
#

why irrelevant?

compact spire
#

Once you have a working example of a projectile using physics, you can apply it to arrows or anything else that you want to be affected by physics.

dapper pewter
# dapper pewter The workaround:

The one problem with this is that each rebinding button is either for keyboard or gamepad and won't allow inputs for the other control type. That's fine, but it also won't accept cancel inputs for the other control type, which would fail Steam full controller support requirements as the player could get into a situation where they are forced to use a keyboard. So I think I will need to add a cancel check in Update

loud heath
#

I keep on getting a NullReferenceException for line 19 in my PlayerHealthBarUI.cs file. This is the line of code: "playerHealthManager.OnHealthChanged += HealthManager_OnHealthChanged; I'm confused and could someone try helping? Thank you in advance

dapper pewter
#

Presumably playerHealthManager is null, is that component definitely in an active parent object?

leaden ice
#

You're dereferencing a null reference

heady iris
#

sneaking this into my library somewhere

leaden ice
#

Boo

#

Easy for people who read stack traces though

heady iris
#

I bet you can construct a completely fake stack trace

short flare
#

pls help. Whenever i make a new project, this shows up and i cannot playtest.

leaden ice
#

Assuming you're not using it

leaden ice
#

From the package manager of course

short flare
#

oh ok thanks

short flare
#

is there any other cuases?

#

it said sometghing about a memory leak

leaden ice
#

Show the list

short flare
leaden ice
#

Show in the package manager

short flare
#

oh

leaden ice
short flare
#

what does that do?

short flare
leaden ice
#

In the project folder

#

It gets rid of stale crap

short flare
#

i dont see a project folder

cosmic rain
short flare
leaden ice
short flare
#

ok, how do i do that

cosmic rain
short flare
#

this is it right?

cosmic rain
#

Not in unity...

short flare
#

in files??

cosmic rain
#

Yes. In file explorer

#

And anyways, the folder you selected is "packages". No where near "project folder".

#

Well, actually near. It's a child folder of the project folder.

short flare
cosmic rain
#

If you don't know, look in the hub. It tells you where.

#

That is the project folder.
Open it in windows file explorer or whatever your os has. And look at the contents.

wide totem
#

Hello, I wanted some advice on a pathfinding system i was going to build for an enemy that can climb walls.
Currently, my idea is to have the enemy do the following steps
1 - get the general direction of goal (either front or back)
2 - shoot a raycast in that direction until it collides with a ground object
3 - shoot a raycast upwards/downwards
4 - (where one of my problem is) somehow detect where the 'wall' ends
5 - repeat 2-4

#

oops didnt mean to hit enter

wide totem
#

ive triedto search this but havent found anything relating to climbing enemies

visual fjord
#

Why the coroutine is stopping?

using System.Collections;
using Unity.Burst.Intrinsics;
using UnityEngine;

public class Spawn_enemy_1 : MonoBehaviour
{
    [SerializeField] GameObject enemy_1;
    [SerializeField] SpaceShipController playerShip;
    [SerializeField] Spawn_player spawn_Player;

    void Start()
    {
        playerShip.playerSpawn += StopSpawnEnemy1;
        // spawn_Player.ContinueSpawnEnemies += ResumeSpawnEnemy1;
        StartCoroutine(SpawnEnemy1());
    }

    void OnDisable()
    {
        playerShip.playerSpawn -= StopSpawnEnemy1;
        // spawn_Player.ContinueSpawnEnemies -= ResumeSpawnEnemy1;
    }

    IEnumerator SpawnEnemy1()
    {
        yield return new WaitForSeconds(1.5f);
        Instantiate(enemy_1, transform.position + new Vector3(37.3f, Random.Range(-17.6f, 7.86f), 23f), Quaternion.identity);
        StartCoroutine(SpawnEnemy1());
        Debug.Log("Lanzando enemigos");
    }

    void StopSpawnEnemy1()
    {
        StopCoroutine(SpawnEnemy1());
        Debug.Log("No lanzar enemigos");
    }

    // void ResumeSpawnEnemy1()
    // {
    //     StartCoroutine(SpawnEnemy1());
    // }
}

visual fjord
dusk apex
#

Are you manually stopping the coroutine?

#

Maybe you should explain what's happening and what's not.

#

ie stop spawn enemy shouldn't have been called but it is etc

visual fjord
#

Well, the coroutine 1 spawn enemies, when shoot an event, the function of this event stop coroutine 1

scenic pewter
#

okay im making this really basic flappy bird game, but im coming across the weirdest thing, im coding a script for the camera to follow the player, its overcomplicated because im trying to fix this bug, where when the game starts, the player just disappears, if i comment the script, the player no longer disappears, why does this happen?

#

like ive never had this happen

somber nacelle
#

your camera is too close to the player for it to render. you need to put the camera at or below -10 on the Z axis and your player and other objects should be at or above 0. this is the typical pattern used to ensure that issue never happens, though realistically you only need it at least as far away as the camera's near clipping plane

scenic pewter
somber nacelle
#

your code sets it to 0

scenic pewter
#

ohh right

#

im dumb thanks

somber nacelle
#

but also for flappy bird, you typically wouldn't need to move the bird and camera along the x axis. the pipes would be moving along the x axis

scenic pewter
#

right, thanks

compact spire
#

@wheat spruce I did end up checking out Stateless. After fighting with it to get it installed (I tried as a nuget package... that didn't work). I've gotten used to it and I think it's going to save me a lot of work.

warm badger
#

how do i remove or destroy the combined mesh that was created by StaticBatchingUtility.Combine? without using resource.unloadunused...() @cosmic rain can you help me regarding this?

cunning lion
#

Hi! I have started to use localization package and dont understand what is the best way to get any information from it? Like its neccessary to wait until LocalizationSettings are initialized, before it starts return any data, so what optio do I have to wait for initialization complete?

Option 1 I see is, (but it doesnt looks like 100% guarantee to fully initialized localization before usage)
IEnumerator Start() {
yield return LocalizationSettings.InitializationOperation;
//next code here in hopes that all methods of this class will be called only after 'Start' execution is finished
}

Option 2 I see is call wait coroutine for each method of this class, but it looks kinda weird

IEnumerator WaitForLocaleInitializationCoroutine(Action action) {
isInitialized = false;
yield return LocalizationSettings.InitializationOperation;
isInitialized = true;
action.Invoke();
}

public void ExecuteAfterInitialization(Action action) {
    StartCoroutine(WaitForLocaleInitializationCoroutine(action));
}

Do you have any ideas how to make it possible call methods of this class in another classes dont thinking about is 'LocalizationSetttings' initialized or not?

wheat spruce
#

It's mermaid graph feature also turned out to be a really helpful way to see how the machine is set up. Especially to help catch situations where the machine wasn't set up how I expected

warm rover
#

Is there anyway to generate links in runtime

#

nothing works

#

build settings dont

soft shard
# warm rover build settings dont

Why might you need build settings to generate links? Links for what specifically? Like a hyperlink that takes you out of the game and to a browser webpage? Or a different kind of "link"?

soft shard
# warm rover offmeshlinks for navmesh

Ah, sadly I am not familiar enough with NavMesh API to help there - build settings is usually used for choosing the scenes that will be built with a playable version of your game, I assume you meant the nav mesh bake settings which I believe you can do at runtime, though im not sure if that applies for links as well - have you already checked the docs for info about it?

warm rover
soft shard
# warm rover ive checked everything including the dll source codes and stuff its ashame i mig...

Hmm, that would give you more control over features and optimization, though it could also be time consuming to build, if you already looked through the github source code, maybe you can try looking for potential solutions on the asset store or other non-official git projects, or possibly try asking again with more details on your research and goals later when more devs might be awake

warm rover
soft shard
wheat spruce
#

I'm sorting out my code for the whole terrain system I'm writing. I have a very bad habit of taking a class that should only ever be very simple, then overcomplicating it by adding far too much in.
For instance in my Grid, I ended up adding a lot of logic and functions to it, but all the Grid actually needs is to be very minimal like:

public class Grid
{
public const int CellSize = 0;
public int Width { get; set; }
public int Height { get; set; }
}```

What I'm wondering is what the smart way to build on top of my Grid, without actually going in and messing its simple definition.
#

Its a side of C#/OOP that I've not played around with all that much

#

My only real idea is that I want to use the Grid as the base for anything that is based around the grid such as public class TileMap : Grid

wheat spruce
#

Thats good when I want to make a whole class do something based on a Grid. But its not actually doing anything special with the Grid class itself.

#

Part of what I had in my Grid before was for it to use my Rectangle class

public Grid(Rectangle rectangle){
  GridWidth = Mathf.RoundToInt(rectangle.Width + Padding);
  GridHeight = Mathf.RoundToInt(rectangle.Height + Padding);
}
public void SetSizeFromRect(Rectangle rectangle){
  GridWidth = Mathf.RoundToInt(rectangle.Width + Padding);
  GridHeight = Mathf.RoundToInt(rectangle.Height + Padding);
}```
#

I dont know if it could be possible to do it, but could I do something as if my Grid was a partial class (not that partial is actually what I need)

public partial class Grid{
int Width, Height;
{

public partial class Grid.viaRectangle{
rectangle MyShape;
SetSizeFromRect()
{```Like I could leave the Grid itself unchanged, but have some secondary version that lets me build onto the base
#

๐Ÿค” have I somehow explained dependency injection? its something ive heard of but havent ever used

mossy snow
#

I would avoid clever code. Your example so far seems like something reasonable for Grid to have

vestal arch
wheat spruce
vestal arch
#

rounding is more for approximation or for display, not for literal float to int conversion

wheat spruce
mossy snow
#

if Grid starts having things that don't apply to all grids, you probably want composition instead. Maybe things need a grid, instead of things BEING grids

vestal arch
wheat spruce
#

I just mean that Grid should only ever be extremely basic

#

nothing fancy is needed for it, especially having grid depend on other classes even when Grid will commonly be used with those

#

"oh I need a rectangle to set grid dimensions, so let me make Grid have to contain a rectangle"

vestal arch
wheat spruce
#

I know Unity has a class for it, but I'd rather have my own shape implemetation

mossy snow
#

if your Grid consists of what you have listed so far (parameters + constructor and a function that just rounds some ints), I'd say it's arguing for its own deletion instead because it doesn't really do anything particularly useful worth existing over

vestal arch
#

why?

wheat spruce
# vestal arch why?

main reason, the classes themselves are extremely basic so its not much extra work to create them

#

also it doesnt lock my code to only work explicitly with the unity API

vestal arch
vestal arch
wheat spruce
vestal arch
#

it isn't even related to remaking them

#

"it's not hard" isn't a reason to make them, it's just a lack of a reason against making them lol

#

making a paper airplane isn't hard, but that's not a reason to make them
maybe you wanted to, now that's a reason

wheat spruce
#

I guess deep down, its a preference thing

vestal arch
wheat spruce
#

that is a factor, but its not like I'm making the entirety of my code be able to be standalone from unity

#

I am using Unity afterall

#

ive always felt more comfortable working in a way where my project wont be fused completely with something

vestal arch
#

i mean if you're only going to be using it for unity, i'd (softly) recommend using unity's stuff so it can integrate with other unity stuff without having to convert all the time

wheat spruce
#

I think Rectangles are the only things Unity has that I probably could use without implementing again

vestal arch
#

if you think you would maybe want to extract it and use it for some non-unity-related case, or perhaps port it to a different context, then yeah that'd be a solid reason to make your own stuff

#

but having stuff very similar to unity's but just slightly different might cause you some pain in the future, like confusing your own rect with unity's rect, for example
like, in the context of your grid, your rect might be integral, but unity's Rect is floating-point, while RectInt is integral

#

also if you get used to unity's api, muscle memory might make it inconvenient to use your own api, and vice versa

#

to be clear; im not exactly trying to convince you to use unity's stuff, im just mentioning this as stuff to keep in mind if you do decide to make your own api

wheat spruce
#

I'm pretty careful these days when it comes to making sure I dont use the wrong class, its caused me problems before where I hadnt realised why I couldnt call certain functions that I knew were in my class

vestal arch
#

something you might not be able to foresee is how your future self will interact with those systems, if your future self will have that same mindset

#

never get too confident with this stuff lol, it'll come crashing down...
-# definitely not speaking from experience... lamy_pain

#

if you're making anything long-term, make it so a stranger would be ok with it, since that's effectively what your future self is to your current self

cold parrot
wheat spruce
#

other thing to note is I'll have a number of different geometry objects, because if I have PolyShape CircleShape LineShape HexagonShape BoxShape etc, all with their own Polygon, Circle, Line, Hexagon geometry struct, but only BoxShape uses Unity.Rectangle

vestal arch
#

hmm that inconsistency could be a problem

wheat spruce
#

if I change the grid size, all I have to do is update the base Grid, and my different tilemaps will both be the same after

#

its the derived classes that have the actual stuff that gets placed inside the grid

warm rover
cold parrot
wheat spruce
#

aah, got ya

cold parrot
#

you do whatever feels right to you, else you you won't know when you go off track. You can always do it different next time. Following advice that you don't feel yet leads to more problems than something that is objectively "not ideal" but well understood by you. All code that was ever written is "bad" by some metric, and those who think their code is great are just naive.

wheat spruce
#

also with the dependency injection thing, I sort of understand the idea of it. Could it be used for something like this?

class RectangleGrid
{
public RectangleGrid(Rectangle) : Grid()
}```As in RectangleGrid itself behaves and is used exactly like Grid. I could use a Grid or RectangleGrid to both make a TileMap, but now my RectangleGrid is specially intended to be used with a Rectangle
#

I just really want to avoid adding loads of extra stuff into the main Grid class, its whats got me into the mess I have where very simple classes end up being impossible to manage if I get carried away

wheat spruce
#
  internal class Grid
  {
    // dimensions of cell
    public const int CellSize = 1;

    // dimensions of grid
    public int Width => _rect?.WidthRound ?? 1;
    public int Height => _rect?.HeightRound ?? 1;

    private Rectangle? _rect;
  }```I suppose this could work, rectangle now is an optional way for the grid to automatically set the dimensions from it, defaulting to a size of 1 when its not set
marsh geode
#

hey fellas, I'm using Newtonsoft.Json along with my unity project since JsonUtility seems limited, but when I serialize something like a Vector2 it adds useless information like

          "x": -0.97618705,
          "y": -0.216930449,
          "magnitude": 1.0,
          "sqrMagnitude": 1.0
        },```

is there any way to exclude this?
wheat spruce
#

because thats what a Vector2 is

sage latch
wheat spruce
#

if its only the position you want, just use a tuple (float x, float y) and serialize that and then reconstruct the vector2 when you deserialise

#

at least that is if json supports tuples

#

if not, just two different floats

pulsar ocean
#

Hey,
I have a Coroutine where I want to set the Material of an Object to a glow Material for a few seconds. The code I have does work fine during testing in the editor bit it somehow won't change the Material during runtime. I've tested if it calls the method and it does, every part of it gets called (at least the parts I could check: the emission color, the waitforseconds, etc.). Can someone help me? What am I doing wrong?

IEnumerator Glow()
        {
            Material glowMaterial = new Material(originalMaterial);
            glowMaterial.EnableKeyword("_EMISSION");
            glowMaterial.SetColor("_EmissionColor", glowColor * glowIntensity);
            rend.material = glowMaterial;

            yield return new WaitForSeconds(glowTime);
            
            rend.material = originalMaterial;
        }
surreal thorn
#

Hello, did anyone have this issue?

#

The project was working fine on another computer a year ago, but when i imported it onto a new system just now, it gives me this.

thin aurora
#

@marsh geode Use this package ๐Ÿ‘‡

#

For some reason the Unity devs are unable to add proper support for proper serializers and therefore their bad conventions interfere with serializers like Newtonsoft and STJ. The issue is that JsonUtility by default serializes fields but Newtonsoft and other serializers use properties. In this case Unity has properties that should not be included but rather ignored, but this is not done by default.

#

This package basically fixes all the types. I'm pretty sure you just need to add it and it will work out of the box

thin aurora
#

If it worked before, perhaps it somehow left something out

#

Otherwise this package is just broken

surreal thorn
surreal thorn
thin aurora
#

If you didn't edit it then it's simply not compiling due to a missing namespace

#

Hard to say because I never used it

surreal thorn
#

It's weird but the Visual Studio doesn't highlight any problems when I open up these scripts

thin aurora
#

I suggest you check for errors

thin aurora
#

Maybe you have unsaved files?

marsh geode
thin aurora
#

It is possible you have unsaved files that do end up fixing the issue, but these won't be included during compilation

pulsar ocean
thin aurora
#

I suggest you check if the objects exist and/or if the objects it tries to set the material on match

#

Specifically whatever rend is

zenith zealot
#

silly question, can you do a bar fill with sprites instead of UI elements? every tutorial im finding is about the UI

#

I have an arrow for aiming and I want it to fill and unfill to show the power behind the shot. I feel this would work better as not part of the UI

pulsar ocean
# thin aurora Hard to say from the code you supplied

I noticed that it works if I put another object in the scene with the urp lit shader (the same shader my other material uses) that has emission enabled. But what if I don't want that? I don't want to include another object with emission enabled into the scene just for this material to be able to use emission. (and rend is the Renderer)

zenith zealot
#

in fact, using a UI would not be feasible at all due to the nature of this

zenith zealot
#

actually, could a sprite mask work i wonder

spare dome
#

don't crosspost

balmy plume
#

sorry

young tapir
#

If I have two non-kinematic rigidbodies, each with a collider and custom component listening for OnCollisionEnter, and they collide. Will both OnCollisionEnter methods create a separate Collision or do they share one between them?

I'm mainly asking because I'm trying to make my collision system a little more intuitive but I can't think of a better way to stop both scripts play a sound on collision other than adding a tiny delay between when they can play.

leaden ice
#

they simply call OnTriggerEnter

#

with teh Collider as a parameter

#

it will run on both objects

heady iris
#

You can compare your instance ID to the other side's instance ID to prevent two sounds from playing at once

#

(check the ID of your game object vs. that of the other game object)

young tapir
#

I meant to say CollisionEnter, not trigger

heady iris
#

Keep in mind that OnTriggerEnter will run on the object with the Rigidbody on it

leaden ice
#

yes - simple trick:

if (gameObject.GetInstanceID() < other.gameObject.GetInstanceID())```
heady iris
#

ah, okay, so you do get a colliison

heady iris
#

compare the instance IDs of the rigidbodies

leaden ice
heady iris
#

that prevents any ambiguity

#

non-kinematic

leaden ice
#

you need at least one dynamic body

#

oh

#

I misread

heady iris
#

not non-non-kinematic

#

๐Ÿ˜‰

leaden ice
#

anyway yeah, the whole instance id thing is relevant

heady iris
#

Instance IDs are unpredictable, but they are very useful for creating an ordering between objects!

young tapir
heady iris
#

If this is turned on, every single OnCollision* method is passed the same Collision instance

#

the values just get swapped out

young tapir
heady iris
#

I don't follow.

#

I'm just talking about the actual Collision object

heady iris
young tapir
#

I find it kind of tricky to put into words

heady iris
#

If you have a component on both objects that implements the OnCollisionEnter method, the method will get called twice -- once on each instance of the component

#

The collision object (which you should not call "other" -- that sounds like what you'd name the Collider parameter for OnTriggerEnter) will contain information about the collision

#

if we call these two objects "A" and "B", then A's OnCollisionEnter callback will point to B's rigdibody and collider

#

and vice-versa

young tapir
#

I can compare A's collider to B, but it'd also be compared in B, to A

heady iris
#

What is the actual problem?

zenith zealot
#

ayyy a spriate mask worked

balmy plume
leaden ice
#

I don't really think their question was actually about the Collision instances. They were really asking if OCE gets called once or twice

balmy plume
#

if both gameobjects have the method then both of them will call it

young tapir
#

I'm curious if they create two Collision instances when they collide, I know both will call OnCollisionEnter

#

But if they do, that's annoying

balmy plume
heady iris
#

This would only matter if you were, say, putting the Collision objects into a hash set

young tapir
heady iris
#

You keep saying "two Collision instances"

#

This makes it sound lke you're asking if the two invocations of OnCollisionEnter get passed the same object or a different object

leaden ice
heady iris
#

I think you're asking about whether you get two callbacks, yes

young tapir
#

As far as I know or understand, I've answered your questions as best I can.

heady iris
young tapir
#

Which I am, as of current, looking into

leaden ice
young tapir
#

A small screenshot isn't exactly helpful and Im slightly concerned I'll get my head bitten off if I ask where it is ๐Ÿ˜›

heady iris
#

I still do not understand how this is relevant, though

heady iris
#

Your actual problem is "how do I only play one sound when a collision happens?"

#

Whether or not the Collision object is re-used is irrelevant

leaden ice
balmy plume
heady iris
#

Collision is not a unity object.

#

It does not have an instance ID.

leaden ice
heady iris
mossy shard
#

does anybody know why i get these random errors when i actually do nothing?

#

they just like sometimes decide to appear

balmy plume
leaden ice
young tapir
leaden ice
heady iris
heady iris
#

You're clearly getting XY-problem'd here and I'm trying to steer you back to your original problem

mossy shard
young tapir
leaden ice
leaden ice
young tapir
#

Maybe we should all be more mindful of how others might perceive a potentially negative comment on a text app, where you can't properly gauge someone's intent ๐Ÿ˜„

mossy shard
leaden ice
#

If indeed it's coming entirely from Unity stuff, it rules out a problem in your code, for the most part

#

Deductive reasoning.

zenith zealot
#

lmao

#

yes thats pretty much what i did

#

tho i used scale in my code to basically scale the size of it in relation to the power of the shot, filling an amount of the aiming arrow proportional to the power of the shot

vague surge
#

Anyone implemented Meta AvatarSDK in Unity6? i feel like the doc is outdated but there's no incompatibility warning from meta (i've noticed prefab are missing, Oculus/Avatar2 folder doesn't have anything useful inside)

zenith zealot
scarlet plank
#

Does anyone know how i could create random room generation for a backrooms game

mossy shard
#

in theory is it better to put a bunch of if's and call them async in the update or only have a while

#

idk how unity handles loops in the update, so i ask

latent latch
#

update itself is just one large loop

vestal arch
#

unity doesn't handle loops in update, the runtime does
unity just says when to call update

latent latch
#

I wouldn't really use while loops in update unless you know what you're doing. Just stick to for loops and add your constraints onto that

latent latch
#

coroutines are an exception though

latent latch
balmy plume
latent latch
#

obviously you can fall into that problem with for loops, but you're still usually adding some constraint onto those so less likely to fall into that problem

mossy shard
#

so all the unity code can stop in an infinte loop?

mossy shard
balmy plume
mossy shard
#

plus it takes a while to calculate

heady iris
#

Unity executes one thing at a time.

#

It's not running a bunch of methods simultaneously (at least, not generally)

#

Some things are run in parallel, of course

#

but all of those MonoBehaviour messages (Start, Awake, Update, OnCollisionEnter, ...) sure ain't

wheat spruce
#
internal abstract class Grid
{
  public static Point[] PointMap;

  public T[] InitializeArray<T>(Func<int, int, T> factory)
  {
    ...
  }

  public Grid()
  {
    if(PointMap == null)
    {
      PointMap = InitializeArray((x, y) => new Point(x, y));
    }
  }
}```Got a similar thing where the static property isnt being cleared when the game is stopped, but I cant do `Grid.PointMap = null` because Grid is abstract
#

not too sure why I cant even access it from my tilemap class, which is class TileMap : Grid

heady iris
#

don't access it from an instance

#

you have to access it from the type name itself

wheat spruce
#

ooooohhhh

#

of course

heady iris
#

note that this isn't giving a separate PointMap field to every child of Grid

#

there is one and only one PointMap field

wheat spruce
#

yeah, shared between both

mossy shard
heady iris
#

Not if you want to be able to touch Unity objects

#

That must happen from the main thread

#

the Jobs system exists to let you do work on other threads (including stuff like mass-updating Transforms)

#

but you can't just flip a switch and run eight Update methods simultaneously

wheat spruce
#

what is it youre doing to make it so slow?

mossy shard
wheat spruce
#

yeah, you said it was taking a while to run

#

could be a case that you accidentally wrote the loop in a way that it's doing extra work, making it slow to execute

mossy shard
#

i have cooked the most monstrous enemy AI known to mankind๐Ÿ—ฃ๏ธ ๐Ÿ”ฅ

heady iris
#

If you can gather all of the information you need all at once and then never touch a Unity object again, you can pretty easily do that in a Job

mossy shard
heady iris
#

anything that's derived from UnityEngine.Object

#

game objects, components, etc.

#

You're not allowed to interact with the Unity API from anywhere but the main thread most of the time

#

So, if you can make a big list of numbers and then go do a bunch of thinking about those numbers, you can do that in a Job (and run it on another thread)

mossy shard
#

oki

#

all i needed

#

thank u

heady iris
#

If you're doing a ton of number crunching, you can also look at Burst

#

It can compile a subset of C# to native code, which is double-plus fast

#

I use this for code that does gradient descent, for example

#

I run it in a burst-compiled job on another thread

#

...well, I could, but I currently just run it on the main thread

balmy plume
#

i thought burst was very unforgiving about memory leaks?

heady iris
#

There are rules about how long your allocations can live, I suppose

#

e.g. a Temp allocation can't be used in a job at all, and a TempJob allocation is supposed to live just four frames

#

But that's a Job thing

#

maybe you're thinking of things like out-of-bounds memory access?

#

Burst has safety checks in the editor, but I believe those aren't included in the built game

#

(since those checks can have a significant performance impact)

balmy plume
#

idk about it much as i havent used it a lot but one of the few instance that i did it gave tons of warnings that i had to resolve before i could get my code running

rugged pond
#

Hello, can someone help me to solve a problem with player position. Every time i drop item from my inventory my player moved a bit and by commenting code i found problem in this line GameObject newItem = Instantiate(itemPrefab, spawnPosition, Quaternion.identity); but it should not change player position and only use it to spawn object. I've tried to remove offset and then player moved to the right side every time

[SerializeField] private GameObject player;

---

public void DropItem()
{
    Debug.Log($"{itemSO}, {quantity}, {player.transform.position}");
    dropManager.CreateItem(itemSO, quantity, player.transform.position);
    Debug.Log("Item was dropped");
    EmptySlot();
    Debug.Log("Slot was cleared");
}

---

public void CreateItem(ItemSO item, int amount, Vector3 position)
{
    Vector3 randomOffset = new Vector3(
    UnityEngine.Random.Range
        (-1f, 1f),
        0f,
        0f
    );

    Vector3 spawnPosition = position + randomOffset;

    GameObject newItem = Instantiate(itemPrefab, spawnPosition, Quaternion.identity);

    Item itemComponent = newItem.GetComponent<Item>();
    itemComponent.ExtractSOData(item, amount);
}
heady iris
balmy plume
#

this is a general problem that occurs a lot just spawn the prefap at an offset

rugged pond
#

I've tried to use DropItem w/o any items in active slot and even in this case player moved

#

Oh, i guess i found problem. Game just create empty objects and move player

heady iris
#

well, does it still spawn something?

#

that's all that matters

balmy plume
#

ya cuzz it still passes and spawns an empty object

scarlet plank
#

is there any way that i can save whats i have in play mode to my editor

#

Nvm

balmy plume
#

I dont think that is possible without adding a script for it, its better to just remember the changes and change them in the editor manually

latent latch
#

You can prefab stuff and it will save its state

balmy plume
scarlet plank
#

I just copied and pasted the assets lol

#

Im making a backrooms game it was for wall generation

#

But i can just copy paste the walls

#

Like they were

heady iris
#

you can write code that runs in edit mode

#

you have to be more careful in there, of course -- such as correctly registering new objects with the undo system

grizzled ferry
#

Does anyone know why my MultiColumnListView doesn't display the NoneElement properly?

#

It's just a label

heady iris
#

I forget the name, but there's an "inspect" view (a lot like in a browser's dev tools) to look at the UIToolkit layout

#

That might help

grizzled ferry
#

Does it have to do with the way I'm making it? I'm just instantiating a Visual Tree that contains the message label

table.makeNoneElement = noPlayerPrefsMsg.Instantiate;```
heady iris
#

It kind of looks like the label is displaying in the Value column, instead of taking up the entire row

grizzled ferry
grizzled ferry
grizzled ferry
balmy plume
#

Is there a way to make the camera less choppy ?
So my camera is attached to a parent CameraHolder, and Player object has an empty tranform cameraPostion, and the camera holder's postion is being updated to the cameraPostion's position, player has rigidbody and is set to Interpolate, and still while moving the camera is kinda choppy, is there a better way to implement this?

soft escarp
#

how do i import cinemachine package to my code?

soft escarp
#

i tried everything and settled it with cm

balmy plume
#

could u link the doc for it?

soft escarp
#

idk if there is a doc for it but its a unity package and its pretty easy to set up

balmy plume
balmy plume
soft escarp
balmy plume
soft escarp
#

i have the camera imported for a long time

balmy plume
steady bobcat
spare dome
#

You don't need to use cinemachine but it is recommended by many, if you would want to fix your current issue we would need to see your code

#

I have not used it in a long time

soft escarp
steady bobcat
#

if you use these you have to add references to others to access the code in them (e.g. cinemachine, addressables, unity iap)

balmy plume
# spare dome You don't need to use cinemachine but it is recommended by many, if you would wa...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class CameraRotation : MonoBehaviour
{
    private Vector2 turn;
    private bool isEnabled;
    [SerializeField] private float mouseSens;
    public Transform oreientation;
    private void Awake() {
        isEnabled=false;
    }

    private void Update() {     
        if(Input.GetKeyDown(KeyCode.LeftControl)&&!isEnabled){
            isEnabled=true;
            Cursor.visible=false;
            Cursor.lockState=CursorLockMode.Locked;
        }
        else if(Input.GetKeyDown(KeyCode.LeftControl)&&isEnabled){
            isEnabled=false;
            Cursor.lockState=CursorLockMode.None;
            Cursor.visible=true;
        }
        if(isEnabled)
            enableRotation();
    }

    private void enableRotation(){
        turn.x+=Input.GetAxis("Mouse X")*mouseSens;
        turn.y+=Input.GetAxis("Mouse Y")*mouseSens;
        turn.y=Mathf.Clamp(turn.y,-90f,90);
        transform.rotation=Quaternion.Euler(-turn.y,turn.x,0);
        oreientation.rotation=Quaternion.Euler(0,turn.x,0);
    }
}
#

for the camera postition its just

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraPosition : MonoBehaviour
{
    public Transform cameraPosition;

    private void Update() {
        transform.position=cameraPosition.position;
    }
}
spare dome
#

does it stutter when moving and rotating the camera? If so use lateupdate for the enablerotation function to see if that fixes it

balmy plume
spare dome
#

I would try using lateupdate, other than that I do not see any issues with your code

balmy plume
balmy plume
#

ig i have to look up doc for cinemachine afterall

soft escarp
#

and even when cm stutters try vsync

balmy plume
balmy plume
steady bobcat
#

Cinemachine will make it work as it smoothes out the following and focusing it does. You can do the same manually

heady iris
#

Camera jitter occurs when something changes at a different interval than the framerate

#

such as when you follow a non-interpolated rigidbody

wheat spruce
#
internal class PaintableTexture
{
  public RenderTexture Tex; // texture which the player has painted color onto

  private ComputeShader _painter; // to compute the texture
  private PaintBrushInfo _brush; // properties of the paint brush (brush positon, paint/erase state, size)

  public PaintableTexture()
  {
    TextureExtensions.CreateRenderTexture(out Tex);
  }
}```Is it possible to have some sort of custom texture class? I've got something like this, and I like the idea of making this class itself exist like a normal texture
#

few forum posts ive seen say its not possible to derive a class from RenderTextyre

dry tendon
#

Hey I have recently started with unity and I have an weapon, reload and gun switch function. Tho when I switch the gun I have to shoot before the ammo and mag text updates on screen. How do I fix that?

still jungle
dry tendon
# dry tendon

The SelectWeapon function is in a different script

thin aurora
# dry tendon

This script seems to do multiple things. Behaviour of a weapon, drawing UI, and animation of a weapon.
I could give an answer on fixing it, but the real answer would be that you should separate this script into three different scripts that communicate to eachother through events, rather than compacting them all into a system that now heaivly relies on eachother.

#

That way you also have your own Update method and you can fire without worrying of the UI, for example

dry tendon
#

That sounds complicated

soft shard
wheat spruce
thin aurora
#

Honestly, it sounds like you might need to take more time learning C# basics if this confuses you

#

Events are quite basic

dry tendon
heady iris
still jungle
heady iris
#

i really want to make a game that strictly follows MVC

#

probably alongside trying out rollback multiplayer

still jungle
#

first you have to find good guidance to apply it for unity which is a hard task itself

thin aurora
# dry tendon

In short, you should have a script that handles your input (not necessarily tied to your weapon, just a general input listener), if you fire you tell your weapon component to fire. When you fire, you call an event "OnFire" and your UI hooks onto this event and updates accordingly with the new bullet count. Your weapon class can also play the animation. This is coupling done right.

#

If this is confusing, there is a server full of people who can explain the idea

dry tendon
#

So from what i understood I should make a new script for every single function that does something and make them communicate

thin aurora
#

You don't necessarily need an event here, but why would your weapon care about the UI? The UI cares about the weapon because it needs to know when and what to update on fire, so therefore the role is reversed with an event

thin aurora
#

So general input, the weapon's firing behaviour and animation and the UI would be a good start

#

You could put the input into the weapon, but why should your weapon care about input? It cares about how it should behave

still jungle
dry tendon
thin aurora
#

This isn't scalable anyway. Would you have this code in every single weapon class of every weapon? ๐Ÿค”

dry tendon
balmy plume
dry tendon
#

So all I would have to do it add the weapon script change settings and done

wheat spruce
#

@dry tendon

public class YourWeapon : MonoBehaviour {
void Update() {
  //here is where you would call the different Weapon classes
}}

public class WeaponUI {
//functions that update the UI
//ie to update the ammo count
}

public class WeaponInputEvents {
//events that occur when the player presses buttons
//ie reloading
}

public class WeaponFunctions {
//functions the weapon will use to do its thing
}```Imagine having something like this
dry tendon
#

Alright

still jungle
#

anyway just fixed according to your question the fire have to execute before you change the ui, so just move the fire up

dry tendon
#

Oh wait lemme try

dry tendon
#

I mean I thought about updating the text every few seconds but that would just waste performance

mossy shard
#

How come i only sometimes get this error:

#

and it doesn't effect anything, everything works perfectly

#

it just gets on my nerves

#

i have checked the line where the error appears, the sizes, everything is perfect and works normally, but it just decides to pop up sometimes

latent latch
#

If you're not sure of an error implies, it's worth atleast a google to give you an idea

still jungle
dry tendon
#

Yea just noticed

mossy shard
#

of my lists

#

the exact error speaks of a node that has this error on a specific x and y position, but it works perfectly

dry tendon
still jungle
#

just place the code in switching logic

latent latch
# mossy shard it's due to the sizes

If you're making an infinite type grid, you don't need to populate every index. You should be using the list as a lookup table and only populate/access what's actually instantiated

still jungle
#

anyway you should separate UI logic from the controlling logic

dry tendon
#

Yea i am on that too

mossy shard
#

and that it only pops up SOMETIMES

#

by this point, i believe this is no longer a logical issue but rather an emotional one ๐Ÿ™๐Ÿป ๐Ÿ™๐Ÿป

still jungle
#

if it repeats it means there is logic behind it, so it can be recreated and tracked down

dry tendon
still jungle
#

according to your code standard yes, you can place it in reload but dont forget to first reset the animation then set it to play

#

but in this case your reload will reload the ammo instantly and the animation will keep playing and can be interrupted

dry tendon
#

Except walk

#

And sprint and jump

still jungle
# dry tendon

too much "ifs" to even read the code, i assumed that you dont have implemented it since you ask for it. Yest there is logic that prevent reloading when the animation is playing.

dry tendon
#

I dont even know if the timer is useful

#

I have it set to 3 sec but that doesnt make sense because you can not reload while the animation is playing

still jungle
#

its up to you to program the logic, if you dont need it then remove it

balmy plume
halcyon swallow
#

if i do FindgameobjectwithTag and their are multiple objects sharing that tag
will it create errors? or just pick one of them

#

nevermind it returns an array instead

cosmic rain
dusk apex
#

Unless you've got to do that perhaps consider referencing the object through the Editor inspector or when instantiated, if created during runtime.

halcyon swallow
#

speaking of instantiation
i have some little capsules that duplicate themselves by instancing their own prefab
but the duplicates that are instanced dont have a reference to their prefab
i tried Resources.load() but that only works once, second generation capsules are also missing the reference

rain minnow
#

an object instantiated from a prefab does not have a link or reference to the prefab (unless you manually assign it upon instantiation) . . .

halcyon swallow
#

i tried calling resource load in the awake function but im confused why it only works once

#

i then thought awake was just buggy so put it in update but that ddint do anything either

rain minnow
halcyon swallow
#

are prefabs not allowed to call themselves or something?

rain minnow
halcyon swallow
#

i found out that putting Resources.load inside of the instantiate function worked
Even though that makes little sense

rain minnow
# halcyon swallow yep

here you go; i just tested it. this is a prefab with its own prefab as a variable. i made the prefab spawn itself (using the variable) every five seconds and it worked. each instance had the prefab variable assigned when instantiated . . .

halcyon swallow
#

weird

#

maybe i have some random line of code somewhere preventing it from working like that

rain minnow
#

also, you can't edit the Instantiate method. how are you creating the instance?

halcyon swallow
#

GameObject child = Instantiate(Resources.Load<GameObject>("Creature")
works
creatureprefab = (Resources.Load<GameObject>("Creature")
GameObject child = Instantiate(creatureprefab) does not

rain minnow
rain minnow
#

i just tested this and it worked

    private IEnumerator Start()
    {
        yield return new WaitForSeconds(5f);

        var instance = Resources.Load<Projectile>("Projectile");
        Instantiate(instance, transform);
    }```
each instance still had a reference to the prefab they spawned from . . .
halcyon swallow
#

weird
i have no idea why my code is fucked ๐Ÿคทโ€โ™‚๏ธ

rain minnow
#

why are you using Resources in the first place? typically, you place the prefab in a variable and instantiate that . . .

compact spire
#

Hey everyone, I'm trying to setup a runtime scaling widget and I can't seem to get the algorithm correct for dragging the single axis handles with the mouse along one axis. Anyone aware of a good example they can point me towards?

long flicker
#

is there a way to make a rawimages size expand when hovering over it

#

im guessing it would be done with an event trigger?

thin aurora
#

Just because there are multiple code channels doesnt mean you can post in all of them

long flicker
#

i didnt mean to send int his one

quick token
#

is there a way to have an object follow another objects position, without having it be a child (so it doesn't copy the scale and rotation)

#

for now im just using a general script i made. but i feel like i remember unity having a built in way of doing it

quartz folio
#

Or any of the other constraint components

quick token
#

oh right, i didn't install the animation rigging package yet

#

thanks for the help, i thought unity had some kind of component for it lol

quartz folio
fervent badger
void basalt
# fervent badger

I have a 144hz monitor and I don't seem to have any of these jitter problems that everyone else has. You don't need cinemachine to make unity games run smooth.

fervent badger
# fervent badger

Potential culprit:

using UnityEngine;

public class DerivativeRotation : MonoBehaviour
{
    [SerializeField] Transform Target;

    private void Update()
    {
        transform.eulerAngles = new Vector3(0, Target.eulerAngles.y, 0);
    }
}

The player is taking the rotation of the camera

fervent badger
#

I'll come back to this later. Just had a mental breakdown from this project

void basalt
#

Ideally you should be rotating your rigidbody via either torque or angularVelocity, but I can still get perfectly smooth non jitter movement in my unity projects by forcing the rotation for my first person controllers. I'd imagine cinemachine might be causing issues for you.

wintry crescent
#

Hey just to double check, I'm not crazy that this is the best way to ensure a GameObject/component is valid?

if (myGameObject != null)
{
    if (myGameObject) 
    {
        myGameObject.DoStuff();
    }
}
#

this double if structure seems weird

balmy plume
wintry crescent
vestal arch
vestal arch
balmy plume
wintry crescent
#

why do I remember that I need to check it for null...? was it for components?

robust dome
#

i think he is looking for TryGetComponent

vestal arch
balmy plume
vestal arch
#

for GetComponent, if it doesn't exist it returns null
both null and invalid objects in unity compare equal to null, and are falsy, while valid/existant objects compare unequal to null, and are truthy

quartz folio
wintry crescent
quartz folio
#

Huh I just noticed I says native C#, that should be native C++, but I'll probably remove references to the language from that sentence entirely

balmy plume
#

dude cs is confusing

thin aurora
#

It's not, Unity is

#

Implicit conversion is not something you should just randomly add like this

vestal arch
balmy plume
#

it was my understanding that once an object gets destroyed the reference becomes null like in any other language

thin aurora
#

Nobody would realize that an implicit conversion of a boolean checks if it's destroyed

#

That's just horrible practice

wintry crescent
quartz folio
vestal arch
thin aurora
#

Even better, Unity would have been a lot better if it didn't override the equality check and added implicit boolean conversion, and just added an isDestroyed boolean to check if a gameobject exists

#

But no, we have broken equality checks instead

quartz folio
thin aurora
#

Broken because half the equality checks no longer work the same way as == I should specify

quartz folio
#

The implicit cast to bool is identical

balmy plume
#

so the only way to check the validity of a GameObject is this implicit boolean check?

thin aurora
#

AFAIK yes (and == / !=)

vestal arch
wintry crescent
quartz folio
vestal arch
#

idk why you'd have a double if structure like this for any kind of validity check

wintry crescent
vestal arch
#

if anything it'd be a single if with 2 conditions ANDed together

simple egret
#

Yep never seen this kind of structure before either, both do the same thing for types deriving UnityEngine.Object

wintry crescent
#

wish they fixed that, though

quartz folio
#

They can't

thin aurora
#

Can't fix without breaking everything sadly

simple egret
#

These are not overridable so they can't

wintry crescent
quartz folio
#

Doesn't change anything

vestal arch
#

isn't is a syntax thing, not an operator? it wouldn't be operator overloadable

thin aurora
#

is is pattern matching, so not overrideable

wintry crescent
quartz folio
#

They may choose to refactor this for U 7, requiring everyone to port their code, but I don't have my hopes up

thin aurora
#

People often say that you should prefer is null over == null but that would only make sense if you used a broken null comparison like this

#

Also is is not really supported in Expressions if you care about that, so it can't be applied everywhere

vestal arch
#

i think they mean to not use the overloads

wintry crescent
#

I associate coreCLR with u 7 because if it's not here when u7 is here I'm gonna cry :(

simple egret
sleek bough
quartz folio
wintry crescent
simple egret
#

It would, ?. compiles into a bunch of is not null checks

wintry crescent
vestal arch
#

wouldn't that not work with references not being turned into null

quartz folio
#

It wouldn't, you'd need to still check a property to see if it was destroyed

wintry crescent
#

exactly, ugh :C

quartz folio
#

But at least you would know that null checks would actually be reference checks and not an expensive jump into native code

simple egret
#

Yeah unless they program their own thing to "inject" a supplementary check (with a source generator and an interceptor) it's not doable

wintry crescent
quartz folio
#

We've got an extension method in our project that does the null check and swaps it for a real null so after that point you can use the modern null operators. But most of the code is ECS so it's not used in many places

thin aurora
#

Yeah I feel like you might be best off making some inheriting class on Monobehaviour that overrides the null check a second time and adds an isDestroyed boolean

#

Unfortunately this doesn't work for purely Component inherited classes, though

unique delta
thin aurora
#

So I suggest you debug your file and make sure the code is saved and compiling

#

From the little you shared I get the feeling your editor is not configured, in which case perhaps you might be able to share a screenshot of your editor window to verify

balmy plume
#

not that there is anything wrong with the code, but whatever you are trying to achieve with the code there has to be a better way to write that code to be more user friendly

thin aurora
#

Can't really give my opinion on complexity since this more or less looks like pseudo code and can be anything

wheat spruce
#

I've got my tilemap system to set the material type of each tile (indicated by colour), the goal now is to construct the mesh to represent the terrain.
What I'm unsure of is what would be a decent approach for that.

1: I could generate a different mesh for each material type, like what I did in the second image, then later put all the pieces back together
2: instead of doing it separately, maybe something like marching squares, I go over each tile, figure out what should go there and construct the whole mesh in one place

#

Im leaning towards 2, just as marching squares seems like they'd offer a lot of benefit down the road (especially as I've got a planned idea that will use marching cubes)

unique delta
balmy plume
unique delta
balmy plume
simple egret
#

<@&502884371011731486> scam

heady iris
#

(maybe marching simplexes in 3D)

#

it'd be worth learning for sure

steady bobcat
sacred python
#

how can i map the uv according to the mesh?
i dont want each face to be painted on

heady iris
#

if you want to create a UV map, you'd do that in Blender

#

The default cube's UV map has each face use the entire texture

#

you want an actual unwrapping of the cube

hexed pecan
#

Default coob is unwrapped:

sacred python
#

ok bu what if i have a iregular mesh? like somehing impoted?
later i dont want to use the cube anymore

heady iris
hexed pecan
#

Aah

heady iris
hexed pecan
#

I always associate "default cube" with blender

heady iris
#

true, it made me think of Blender too :p

heady iris
sacred python
#

hmm i understand
thank you guys

wheat spruce
# heady iris it'd be worth learning for sure

yeah, its what I'll do. Made a start designing it in Houdini, gives me instant feedback to see if what I'm writing will work. So far so good with it finding the 4 points for each square

rotund perch
#

is there any possible way to call a delegate remotely? (not in the script)

#

I don't entirely understand delegates yet but I understand the basics of how to use them

heady iris
#

you can pass a delegate typed object around like any other object

#
public void RunIt(System.Action action) {
  action();
}
#

this method will accept any zero-argument function that returns void and immediately execute it

rotund perch
#
  public delegate void OnPlay();
  public static event OnPlay onPlayStarted;

I have this in one script, editorManager

I change scenes then want to call this without an editorManager using my TestLoader script, but it says I can't do editorManager.onPlayStarted(), only use += or -= unless inside editorManager

heady iris
#

event only lets the type that owns it invoke the delegate

#

anyone can add or remove callbacks

#

If you need to be able to invoke onPlayStarted from anywhere, just add a public method that invokes it

rotund perch
#

yeah I've got a public static void startPlayDelegate() => onPlayStarted(); in editorManager but I'm getting

NullReferenceException: Object reference not set to an instance of an object
editorManager.startPlayDelegate () (at Assets/Scripts/editorManager.cs:984)
TestLoader.Start () (at Assets/TestLoader.cs:16)

wintry crescent
#

I have a script (not written by me and pretty complex so it's tough to copy the relevant parts here) that derives from MaskableGraphic. Maskable (the property) is set to true, but the graphic isn't being masked, while its child components (normal text/images) are being properly masked - does anyone have an idea where should I start looking to figure it out?

rotund perch
#

@wintry crescent

wintry crescent
rotund perch
#

huh, that's usually the culprit for me

#

I would check the docs for MaskableGraphic

thin aurora
#

That said, what specifically is line 984 here?

wintry crescent
#

I have a script that makes a rounded rectangle - it works AS the mask, but it doesn't work when it's being masked

thin aurora
#

Note that if this is an event, if nothing is subscribed to it it will be null

rotund perch
wintry crescent
#

as you can see, it masks other things properly...

thin aurora
#

Again, unless onPlayStarted returns a delegate or event

#

Oh I see the code above now

#

It's an event

simple egret
#

Given the name, seems like an event yep

thin aurora
#
-public static void startPlayDelegate() => onPlayStarted();
+public static void startPlayDelegate() => onPlayStarted?();
or
+public static void startPlayDelegate() => onPlayStarted?.Invoke();
rotund perch
#

Maybe my code isn't subscribing to it in time

#

what does the ? do?

thin aurora
#

Null coalescing

simple egret
#

(Runs the stuff after the ?. only if the stuff before is not null)

rotund perch
#

oh cool so I don't need to have a if(x != null) thing

simple egret
#

Yup

rotund perch
#

that will save me a lot of space

thin aurora
#

Or in this case ?() is syntactic sugar for ?.Invoke() I believe

simple egret
#

?. compiles into a full blown if statement, if I remember correctly

#

It's syntax sugar, so there's no performance difference

rotund perch
#

Ok so the issue is that when I do the load function, it instantiates a bunch of objects, but then the objects didn't have time to subscribe to the event. I was using a Start() function to subscribe to it but if I switch it to Awake() it works

heady iris
#

note that you should not use this for Unity object types -- it'll only catch a genuine null

#

a destroyed unity object compares equal to null, but that's not an actual null reference

heady iris
#

I'm not sure where I'd start looking though

ashen oyster
#

Hey is there a nicer way to do this?

    private bool _jump;

    private void Update()
    {
        if (_input.Player.Jump.triggered) _jump = true;
    }

    private void FixedUpdate()
    {
        if (_jump)
        {
            _jump = false;
            PhysicsJump(); //dummy function
        }
    }
rotund perch
#

is this the new input system?

ashen oyster
#

Indeed

rotund perch
#

ok

#

I'm pretty sure there's a buttondown equivalent

#

let me check

vestal arch
#

you could do PhysicsJump in the if in Update directly, depending on what PhysicsJump does

vestal arch
knotty sun
ashen oyster
rotund perch
rotund perch
#

Not sure if WasPressedThisFrame works for fixedUpdate though

vestal arch
vestal arch
ashen oyster
#

So it's crucial where it appear in the fixed updat function

vestal arch
#

then this is probably fine

ashen oyster
#

Well yeah it's fine but I hate how it makes everything so messy ๐Ÿ˜ญ

vestal arch
#

well how exactly do those "other things" edit the velocity?

#

do they not respect the y velocity or something?

ashen oyster
#

They don't

#

If you hit your head it gets set to 0

#

or if you touch the floor!

#

so it would get set 2 -> 0 -> update position, then it doesn't jump

vestal arch
#

why not just let the physics system handle that?

ashen oyster
#

that's a non-option

#

I'm making a precision platformer

vestal arch
#

how is that a non-option?

#

you're literally just redoing what the physics system would already do

ashen oyster
#

I'm not gonna explain why, just know I can't

vestal arch
#

what's the issue when letting physics handle collisions?

ashen oyster
#

It's not, I need fine tuned control over all movement. The physics engine is just in the way

#

I do use a kinematic body