#archived-code-general

1 messages · Page 287 of 1

quartz folio
sturdy cove
#

oooh ty

soft shard
#

The 2 common ways AI is done for games is FSM (Finite State Machines) and BT (Behavior Trees) - FSM is running a single state at a time, for simple AI (like companions, vehicles, Mario-like enemies, etc) this works fine, but when AI need to manage multiple states and complex transitions a BT is more flexible (and also more complicated to implement), in addition to those, AI can also have many "layers" such as pathfinding, obstacle avoidance, flocking logic, "assistance"/aggro (for example: player attacks 1 AI, and 3 nearby AI also respond), goal-oriented/look-ahead, score based (which is how Sims AI decide what to do), weighted decision making (such as Dark Souls), and many other forms ontop of the FMS/BT, there are even Hivemind AI (often used in RTS where you have a lot of AI controlled by 1 system performing their CPU-intensive logic), and threaded simulations (such as how GTA can have activities go on in scenes that arent loaded), proximity and stats can also affect the logic (such as how close to "see" a player, how loud to "hear" a sound, how "accurate" to shoot a gun, etc)

It certainly is a massive topic and there are some GDC talks about specific games taking specific AI approaches such as Sims, Watch Dogs, Assasins Creed, GTA and others, "Game Makers Tool Kit" on YouTube also have lots of video essays about AI design - it just depends how complex of an AI you want to build, and how relevant AI is to your gameplay, I think starting with FSM is certainly the most "simplest" form of AI though, but I donno the scale of your game

vocal cypress
#

Can I chat with you in DMS to share more

#

Behavior trees sound good

#

But AI can also have many "layers" such as pathfinding, obstacle avoidance, flocking logic, "assistance"/aggro (for example: player attacks 1 AI, and 3 nearby AI also respond), is what Im aiming for

#

Ready Or Not style AI

#

And I have 8 days for the deadline

#

publisher request

soft shard
# vocal cypress Can I chat with you in DMS to share more

You can start a thread, maybe others can chime in, im not the best with AI, as most of my projects have never been large enough to need anything more complicated than a FSM with a few "layers" ontop, theres just so much complexity AI can take its a pretty big topic, im not really sure if a complicated system can be built, tested, iterated and scaled within 8 days, though if you have a lot of experience, you could maybe setup a BT in a day or 2, ive seen a UIToolkit tutorial on making a editor for a BT, though havnt attempted it in a practical/commercial project myself

vocal cypress
#

Ah, it was just it was a actual game on Steam and I didnt want to sound self promoting trol

#

I know the goal of the AI cant be completed in 8 days obv, but Im trying to research (currently watching Game Makers Toolkit ;3) the most obvious parts AI development to make them the best I can

heady iris
#

I've been poking around in the depths of the AI Mines for a while

soft shard
#

Ah, so you have an already-released game with a 8-day deadline to update it with a BT-like AI system? (I dont think thatd be self promoting to talk about it in that way)

vocal cypress
#

Its not released yet, and I didnt mean to sound like it was my project, I work just for the studio as a developer

#

It currently has a AI system but its not the games style

heady iris
#

the simplest thing you can do here is to add more randomness

vocal cypress
#

Currently they just push the player with weapons

#

0 self preservation

heady iris
#

if you're concerned about making them feel smarter, then a whizz-bang-fancy AI system may still feel very flat

#

you mostly just need to make the player think the enemy is smart (:

vocal cypress
#

Thats what Im learning from the channel Ive been recommended

heady iris
#

F.E.A.R.'s enemies are constantly yammering

vocal cypress
#

These are the notes im taking lmao

#
- AI should hold their ground more, instead letting the player come to them```
#

its only been 2 minutes

soft shard
heady iris
#

I'm developing a survival horror-y game right now

vocal cypress
#

Thats what I want lol, the AI to be more "dumb" when they know nothing

vocal cypress
heady iris
#

I've implemented GOAP and a complex perception system, but I still need to convey to the player that there's complicated stuff going on :p

#

it's an interesting problem

#

a lot of this is more for my own curiosity's sake

#

this has absolutely not been the most efficient way to implement a game

magic briar
#

Hello. i have real camera, which provide SDK (.NET), how can i add it to Unity? if it is possible?

tardy crypt
#

Much delayed, but FWIW, moving to a separate folder outside of assets and using "Add as Link..." worked, so I'll probably just do tests like that rather than use the UnityEngine unit tests framework, at least for things that are completely independent of the game.

royal wigeon
#

I'm trying to read the documentation here about using InterestGroups, but when I type out VoiceConnection.Client.OpChangeGroups, there is no such thing even though I put all the 'usings' at the top.

limpid siren
#

Hey guys, can anyone see if they know something about this that i have asked?

delicate flax
cosmic rain
#

You can create it at runtime, but it's gonna be a huge waste of resources if you do that every frame.

calm talon
#

I could still use some help with this ^

crimson vault
crimson vault
leaden ice
#

and of course - to have already started a drag operation from elsewhere

crimson vault
#

Oh, i don't have a PhysicsRaycaster2D on my cam. The drag works very well with mu turret component, just the plot doesn't detect the onDrop(). thanks 🙂

#

The PhysicsRaycaster2D on the camera fixed the problem, thank you so much 😭

limpid siren
cosmic rain
limpid siren
#

but whats wrong on my code? can u see it?

#

here

cosmic rain
limpid siren
#

sure the character spawns there in real time btw 1 min

delicate flax
#

did you try to add the line: renderTexture.Create(); that I linked?

limpid siren
#

is working xD i just did shit with the positions ahah

#

thanks dlich ahah too many hours awake

cosmic rain
cosmic rain
fleet gorge
#
    IEnumerator Upload()
    {
        commandField.text = " ";
        text.text = "COOKING UP A RESPONSE...";
        using (UnityWebRequest www = UnityWebRequest.Post("http://xxxx/help/" + commandField.text, new WWWForm()))
        {
            yield return www.SendWebRequest();
            Debug.Log("Complete!");
            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError(www.error);
                text.text = "ERROR: " + www.error;
            }
            else
            {
                text.text = www.downloadHandler.text;
            }
        }
    }

I wanted to send a post request using the unitywebrequest, I've tested my API on postman and it works fine but when bringing it into unity it only gives the error "HTTP:/1.1 404 not found"

#

I enabled allow downloads over http but it still gives this error

#

oh

autumn field
fleet gorge
#

oh i found out why

fleet gorge
#

it is solved 🎊

fleet gorge
#

I have this discrepency between the built version and editor.
I was making a grid for my game using a quad and material; In the editor the grid is the correct size but in the built version the grid is much bigger and becomes misaligned

fleet gorge
#

The grid is a physical object in the world

#

oh wait nvm

#

i attached it to canvas 😨

#

no wonder the transform kept adjusting

jagged snow
#
        {
        };```
I would like to know if it would be possible to unassign this specific event, or would I need to create an action in order to do so?
lean sail
faint nimbus
#

how do I prevent people from flying using objects that we can carry like in zelda?

#

object is also solid, and can reset isgrounded from player when on top(for gravity reset and jumping)

lean sail
faint nimbus
#

it is like, i can hold something and take it with me, but if i stand on the item while i am holding it, and I jump, I take it with me, but i am still on the item, and i fly indefinitely because I am still holding the item which prevents it from falling

#

was wondering what are ways to prevent it, I think it is a common bug/feature in a lot of games

lusty cargo
#

Smol Unity Rant:

You know what really grinds my gears? The fact that Monobehaviour implements "OnDrawGizmos", which is a method that is only used for the Editor. Therefore any builds that have "OnDrawGizmos" will crash unless you manually ignore that method for all Monobehaviours

anyway around this ?

spare quartz
lean sail
cosmic rain
lusty cargo
lusty cargo
cosmic rain
#

And the method is ignored as in isn't called in the build

quartz folio
#

I doubt it is ever called in builds. The attribute solves your problem completely, just look at the docs instead of being a prick, and you can easily exclude the code with preprocessor ifs

lusty cargo
cosmic rain
lusty cargo
cosmic rain
#

Can you provide any proofs? Because it sounds unreasonable.

rare oar
#

does anyone know how to store 2d grid position into a variable and and see what type of grid position such as (0 = floor & 1 = wall & 2 = win)?

lusty cargo
#

i can share proofs just don't know if ill be breaching contracts , thanks for all the feedback guys i have a different method @quartz folio apologies if i came across as a prickle , all love from myside .🤘

cosmic rain
rare oar
#

i've making a ai rat maze, i've already set up the movement, no collisions are used, i used to check what's grid is Infront and other sides of the rat. the problem i have right now is that i will keep going to area's that has been explored and not going towards unexplored area's such as intersections where rat has to go front or right, position which i want to make sure i has a memory array's of which grid it had already explored and what grid hasn't.

fervent furnace
#

your algorithm is incorrect not the grid setup

rare oar
fervent furnace
#

you mean your mouse will stuck in explored area not going to new area, i guess some checking in your visited[] is incorrect
or you want this
https://en.wikipedia.org/wiki/Hamiltonian_path

In the mathematical field of graph theory, a Hamiltonian path (or traceable path) is a path in an undirected or directed graph that visits each vertex exactly once. A Hamiltonian cycle (or Hamiltonian circuit) is a cycle that visits each vertex exactly once. A Hamiltonian path that starts and ends at adjacent vertices can be completed by adding ...

rare oar
#

also i will have a look at this link, thank you.

deep path
#

what do you think about this

fringe knot
#

How do you guys usually performs your checks on your game's performance and stability?

leaden ice
#

Unit tests are a good option

#

Otherwise play testing

hard viper
#

i don’t remember if it is NP or what. It’s been too many years

#

But it is a common problem

hard viper
#

profiler helps find specific methods that might be particularly bad.

#

in my case, i had very fancy RuleTiles which made RefreshTiles() consume 2/3 of the time of my level loading

#

solution: optimize usage of RefreshTiles

#

during play, all the time cost in my game is pretty evenly distributed across different responsibilities. => no clear thing that really needs optimizing

#

profiler also lets you look at lag spikes, which are spots where you want to pay attention because usually that is caused by one specific thing

indigo verge
#

I can think of several ways to do this, ranging from simply iterating over the list and moving around the entries, or having a second list that is used as a resorting buffer, but what is the best practice, if I want to take a List, and insert a value into the middle of it, and also displace all other entries, such that they move up in the index?

Example:

List:
0 Sword
1 Shield
2 Bow

I then attempt to insert an arrow into the list, at index 1, and displace everything after it, like so;

0 Sword
1 Arrow
2 Shield
3 Bow
#

I'm working on my inventory system, and I want a drag and drop functionality that can allow me to drag an item into the list, displacing all the other items to make room for it.

#

On that same note, what is the best practice for removing an item from a list, then "collapsing" the unneeded index?

I take this list:

0 Sword
1 Arrow
2 Shield
3 Bow

and then I try to remove the item in index 2, the other items "sliding back" in the order
Like so:

0 Sword
1 Arrow
2 Bow
knotty sun
#

That is standard functionality of the List class

indigo verge
#

I thought List.Insert overwrote the index?

#

All the documentation I found says it does.

#

And google says I need to make an entirely new list every time I do that

knotty sun
#

No. Insert is insert

#

I don't know what you've been reading, try the MS C# docs

indigo verge
#

So Insert will indeed displace everything else in the list, rather than just overwriting what's in a particular index? and List.RemoveAt doesn't leave an empty index slot behind afterwards?

knotty sun
#

correct

indigo verge
#

Thank you very much. I know it's a silly question, but when I teach myself entirely using google... Well, sometimes that doesn't work.

knotty sun
#

if in doubt about C# the MS docs are where you should be looking not random shit on Google

knotty sun
#

I think he may have confused List with Array looking at his questions

cyan granite
#

code

neon plank
#

Why Object.GetInstanceID() is not thread-safe? It's just an integer read...

knotty sun
heady iris
#
    [SecuritySafeCritical]
    public int GetInstanceID()
    {
        EnsureRunningOnMainThread();
        return m_InstanceID;
    }
neon plank
heady iris
#

it is indeed just spitting out a field

#

Of course, it's possible that another thread could be trying to modify that field at the same time

neon plank
#

The field is initialized during construction and never touched AFAIK

#

Documentation says it doesn't change

harsh root
#

Hey I got a question about perling noise. I want to create a map where its split up in x areas wide and y areas height.
For areas I mean stuff like ocean, Land stuff like that.
I cant figure out how to make this happen. When I play with noise values it either becoems super high or super low. No more natural flow

#

Does anyone know how to make that work with perlin noise

leaden ice
delicate flax
#

you need to combine several layers of noise

#

and interpret them differently

harsh root
#

This is how it normally looks like

#

This is the result with multiple diffrent tries

#

Like adding a depth offset, clamping the values between ranges

harsh root
delicate flax
harsh root
#

aah okay

delicate flax
#

but looking at the images I'm not 100% what it is you are trying to do

harsh root
#

so what I probally want is a general noise layer. Then a noise layer dependant on what I want to achieve in that area

leaden ice
#

It;'s possible you're sampling at integer gridpoints in the noise function and getting the same value everywhere, which is a known property of perlin noise

harsh root
#

The gren squares are basicly the land areas

#

But thanks I'll try and take a look at that

harsh root
rare bough
#

hello does any one knows where and who toask how to make an ui menu for phones i needed some help cause i'm new at making a game also new on the server

heady iris
wise kindle
#

I've got several points in space. They are variable in position and amount. How could I draw the area between them on Gizmos?

#

For example, I can make an object that's a child of this script's, and it would add that object's position to a list

#

I want to be able to draw the area between all of them

heady iris
#

is this going to be a 2D polygon or a 3D polyhedron?

wise kindle
#

2d polygon

heady iris
#

Deciding what area is "inside" a set of points isn't trivial. It'll be easier if you only need a convex hull, though

#

I'm not sure what you'd use to actually fill in the area, though

wise kindle
#

All I want to do is in a sense connect the points, on Gizmos, and I think that would be enough. I'll try handling the area later. For now that is what I need

#

Cause if I do that, I think a gizmos line could work as a trigger of sort, right?

#

And for a non teleporting object, I wouldn't need to use math

remote dirge
#

Hey, quick question, is there a way to make the script automatically swap out the scriptable object attached to it?

#

I'm about to make another scriptable object for the script in question and I'd like to know if there's a function I can do that will swap them automatically.

dusk apex
remote dirge
dusk apex
#

Why not just have an array and reference the next index?

leaden ice
#

yes you can use = to reassign your reference to another object

remote dirge
#

Ah, okay.

#

I'll look into that and see what I can do.

stoic mural
#

I persevered and finally got it working. The solution from the uni was correct for me and it doesn't seem to miss at any point.

 private void RotateToShootPlayer()
    {
        // Rotate tank in direction of player
        var direction = transform.position - player.transform.position;
        var angle = Mathf.Atan2(direction.x, -direction.y) * Mathf.Rad2Deg; 
        barrel.rotation = Quaternion.Euler(Vector3.forward * angle);
        
        // Offset rotation to intersection point
        var o = Vector3.Dot(player.velocity, barrel.right);
        if (Mathf.Abs(o) < bullet.force)
        {
            angle = Mathf.Asin(o / bullet.force) * Mathf.Rad2Deg;
        }
        barrel.Rotate(Vector3.back, angle);
    }

This is the solution. This script rotates the tank barrel and when I instantiate the bullet it is spawned with the barrels rotation and shoots forward.

mental rover
remote dirge
leaden ice
leaden ice
#

This is all kind of vague/abstract without seeing your code

leaden ice
#

you would just do bossData = whateverNewBossDataYouWant; wherever and henever you want/need to change it

remote dirge
#

Okay, sounds good.

stoic mural
stoic mural
leaden ice
#

Or your mental model of things

stoic mural
#

So the y axis is always pointing towards the player

leaden ice
#

that's why you have a weird/backwards atan

#

I would expect e.g.:

        var direction = player.transform.position - transform.position;
        barrel.up = direction;```
#

(you don't actually need to do the trig at all)

#

but your current direction is backwards - it's FROM the player TO the object this script is on

#

The direction vector from A to B is calculated as B - A

unique delta
#

How can i keep track of what scene i m in?

#

For example if the scene 2 is loaded something happens.

leaden ice
unique delta
#

a ok thanks

remote dirge
#

So, I have a problem. I've got the attacking stuff figured out, but when I go into the battle screen, the player suddenly always starts at 0 HP. Here is my script currently: https://hatebin.com/onqsiceisa

#

The last thing I remember adding before this started was the playerHeal thing in Update.

#

I tried removing playerHeal from update and the same thing happens. Does anyone have any idea what's going on?

unique delta
static kite
#

I learnt roblox coding during lockdown for 2 years, and I have grown up and roblox is out my interest however coding still is, I learnt coding with the Roblox LUA Documentation however I cant find a documentation for unity step by step from start to finish

remote dirge
somber nacelle
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

leaden ice
unique delta
#

So I made a save and load system. When I went into another scene, the x,z, and y loads from the first scene and I m falling infinitely. So I was thinking of checking whic scene is loaded and making a load file for every scene. I know it sounds stupid but I can t think of something else.

leaden ice
#

You'd have to explain what you're trying to do

#

"A save load system" is very vague

#

what exactly are you trying to save and load

#

and why would you need a separate file for each scene

unique delta
#

so if i save the x,y,z from the first scene. When i enter the second scene the game loads with x,z,y from the first scene

leaden ice
#

What does "x,y,z from the first scene" mean?

unique delta
#

and the x,z,y aren t the good ones

leaden ice
#

XYZ of WHAT

unique delta
#

of the player

leaden ice
#

so player position

#

You can just use words

unique delta
#

yes

leaden ice
#

All you need to do is capture the actual data you want to save in an object in an understandable way

naive swallow
#

Is the player a DDOL?

terse turtle
#

I need help understanding how a game mechanic works, however it seems difficult to describe. Is it fine to send a Itch io game with the mechanic or is that against the rules?

unique delta
leaden ice
#

For example:

public class PlayerData {
  public int currentLevel;
  public Vector3 position;
}

public class SaveGameData {
  public PlayerData playerData;
}```

If the current level is not the level the player was on, you'd not use the position from the save data here, you'd just use the level's default spawn position @unique delta
naive swallow
naive swallow
unique delta
#

yes

naive swallow
#

If you don't want to save the player's position, why are you saving the player's position

leaden ice
terse turtle
#

The Player is able to hold space, depending on how long you hold space the jump is less or greater. Finally while holding space, you can hold another key for left or right, and when you let go of space it will launch you with the jumpForce accumalated and then left or right depending if you were trying to go those directions.

#

Here the player is holding right, so he will be launched diagonally right up

leaden ice
#

You'll want to map the time held to a range of actual force values of course

#

that could be done with an AnimationCurve or just hardcoded with a Remap function

crimson vault
#

Hi guys, I have a question about best practice.

I have a player and a liana who attack when the player collide with it. I have animation for Liana idle and when liana is attacking.

I have think about detecting the beginning of the attack animation for deal dmg, that's legit ?

soft shard
terse turtle
#
void Update() {
        spacePressed = Input.GetKey(KeyCode.Space);
        spaceLetGo = Input.GetKeyUp(KeyCode.Space);

        float moveInput = Input.GetAxisRaw("Horizontal");

        if (spacePressed) {
            timer = timer + Time.deltaTime;
        }
        if (spaceLetGo) {
            rb.velocity = new Vector2(moveInput * timer, jumpForce * timer);
            TimerZero();
        }
    }``` This code works, but how can I make the X axis be more strong? Currently the Player jumps in the direction of the Direction I want, but it is light. I want it to be a sort of straight diagonal jump that(The Way I am Holding(-1, or +1)) and to be more straight.
crimson vault
terse turtle
#

If this is clearer, I want the player to go either straight up(0 Degrees up), or 45 degrees left or right up.

sudden stump
#

Oh, you didn't mean make it stronger

#

Well, you'd want to make if statements to check the X axis. If it's -1, angle is -45. 0, angle is 0. +1, +45

#

Angle should probably be a field

terse turtle
#

I found the issue*

#

It was the gravity. I just need it to be less when the player is launched. Thanks for the help!

sudden stump
#

🚬

molten isle
#

!code

tawny elkBOT
molten isle
#

I have stumbled on a problem I can't seem to find a solution to. I have a player movement script that has wallrunning, dashing etc, but it doesn't work on moving platforms, the character just falls off. I tried parenting the moving platform or playing with the forces on the rigidbody but I couldn’t quite figure it out and I failed. Is there an easy solution to the problem? Here is the player movement code: https://gdl.space/vebuwufime.cs

cyan granite
#

ng

molten isle
sudden stump
#

OnCollisionStay, player speed += platform speed

#

Or just do it with any rigidbody so nothing would fall, not just the player

#

This is all theoretical though

molten isle
cyan granite
humble kraken
#

I am making a projectile system for my moba game, similar to LoL. I use it for dashes, jumps, kb and skill shots. I have a a missile manager that on update moves all projectiles based on the data stored. Each projectile has point A (launch point) and point B (end point). Projectiles can fly in curves, arc and various forms. Upon building the system, I realised that I use rigibod body and collider to fire an event upon projectile hitting something. This is probably not very efficient. What is a good way to optimise it? (Later in the game, i will have walls that block projectiles or teleport projectiles or projectile hitting another projectile).

vital oracle
#

For something like a dungeon crawler with turn based combat. Would you have one state machine that includes all states or one for the gameplay outside of battle and one just for the battle?

leaden ice
leaden ice
humble kraken
#

but, it seems that it will be hard to implement with my feature requirment

leaden ice
#

why reimplement the wheel

humble kraken
leaden ice
#

Test it - I'm sure PhysX is going to be faster than your scripts

elfin tree
#

I use the following code to drag and drop rigidbodies, only thing is it breaks when I rotate the camera, it's in update so I'm not quite sure what I'm missing, thoughts?

#
private void Update() {
        if (!_targetCamera)
            return;

        if (Input.GetMouseButtonDown(0)) {
            // Check if we are hovering over Rigidbody, if so, select it
            _selectedRigidbody = GetRigidbodyFromMouseClick();
        }

        if (Input.GetMouseButtonUp(0) && _selectedRigidbody) {
            // Release selected Rigidbody if there any
            _selectedRigidbody = null;
        }
}

private void FixedUpdate() {
  if (_selectedRigidbody) {
    Vector3 mousePositionOffset =
       _targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,
          _selectionDistance)) - _originalScreenTargetPosition;
                
    _selectedRigidbody.velocity = (_originalRigidbodyPos - _selectedRigidbody.transform.position + new Vector3(
                mousePositionOffset.x,
                mousePositionOffset.z + RAISE_AMOUNT,
                mousePositionOffset.y
            )) * forceAmount * Time.deltaTime;
        }
}

Rigidbody GetRigidbodyFromMouseClick() {
        Debug.Log("handling");
        var ray = _targetCamera.ScreenPointToRay(Input.mousePosition);
        var hit = Physics.Raycast(ray, out var hitInfo, RAYCAST_MAX_DISTANCE, layerMask, RAYCAST_QUERY_TRIGGER_INTERACTION);
        if (hit) {
            if (hitInfo.collider.gameObject.GetComponent<Rigidbody>()) {
                _selectionDistance = Vector3.Distance(ray.origin, hitInfo.point);
                _originalScreenTargetPosition = _targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
                    Input.mousePosition.y, _selectionDistance));
                _originalRigidbodyPos = hitInfo.collider.transform.position;
                return hitInfo.collider.gameObject.GetComponent<Rigidbody>();
            }
        }
        return null;
}```
heady iris
#

in what way does it "break"?

elfin tree
#

It just drags in the wrong axis

#

So lets say I don't rotate the camera it works perfectly

#

But then it seems like it still moves in the same axises(?) even tho the camera is rotated

#

I think it's cause GetRigidbodyFromMouseClick, only happens once? (possibly)

heady iris
#

Yeah, since you're remembering its original screen position. Moving the camera changes the object's screen position

#

oh, that's actually a world position

#

you should name that variable something more descriptive :p

#

My first guess for this problem would be to compare the current screen position of the object to the current screen position of the mouse

#

and to compute a velocity vector based on that

elfin tree
#

Yeah, maybe I need to rework the whole thing

#

It's some old code from another project I prolly found somewhere I assume

elfin tree
#

Have to go though, will keep at it a bit later

heady iris
#

btw, if you want to drag something around on a constant Y-level, consider using Plane and Plane.Raycast

#

you can create a plane that goes through the object's position and with a normal that points up

#

then raycast onto that plane to get a world position based on a screen position

indigo verge
#

Is a null value in a function the same as not passing a value to that function, for the purpose of Overrides?

I.E

public void AddItem(ItemObject _item)
{
//Blah Blah Blah
}

public void AddItem(ItemObject _item, int _slot)
{
//Blah Blah Blah
}

Let's say this function, and it's override, are called by dragging something into your inventory.

If it is dragged onto a slot, it sets the slot variable. But if it isn't hovering over a specific slot in the inventory, the slot would be null.

In that situation, is

AddItem(Item, Null)

the same as

AddItem(Item)

?

heady iris
#

in this case, null is incompatible with the int type, so that'd be a compile error

#

more generally, no, they are not the same

indigo verge
#

So basically, in the drag and drop system itself, I have to add null handling to choose between the two functions.

#

And only pass a value if one exists.

#

Thank you very much, I don't know if this was a dumb question or not, but I wasn't able to find an answer in the documentation

heady iris
#

C# tries to resolve the method group by looking at the number of arguments you passed, as well as their types.

#
    public void Test()
    {
        Foo(3, null);
    }

    void Foo(int x)
    {
        
    }

    void Foo(int x, int y)
    {

    }

    void Foo(int x, GameObject y)
    {

    }

    void Foo(int x, Transform y)
    {

    }

This is a compile error because it can't decide if you wanted the third or fourth method

#

Getting rid of the last method makes it work, and it winds up calling the GameObject-taking method

indigo verge
#

That makes a lot of sense. Thank you for explaining. What is best practice for sanitizing this? I'm assuming it's simply to make sure to check for null, before deciding whether or not to run the normal version or the override.

heady iris
#

I'd think that the drag-and-drop code should always call the method that takes a slot index

#

unless you can drop an item somewhere to just put it in the first available slot

#

in that case, you'd still have two different code paths

#

one for dropping an item on a slot, and one for when you don't

indigo verge
hidden flicker
#

How do I fix this problem?
My code reads the normal of the surface below it to determine the move direction. This works fine on flat surfaces or very shallow slopes, but if the player is at a certain point on the slope, it reads the normal of the ground and uses that to determine move direction, instead of the desired result, which is reading the normal of the slope as soon as it touches it. This problem has plagued me for weeks and it haunts me to this day

#

Here's a diagram of the issue

indigo verge
#

Warning, however, spherecast is... weird.

#

I don't remember the details, but Spherecast has a bunch of weird bugs associated with it.

hidden flicker
#

It's ok I just want it fixed 💀

indigo verge
#

I just remember it took me longer to work around the spherecast bugs than it did to make the entire movement system.

#

Actually, I might have straight up switched it for a dedicated hitbox.

#

Let me check and I'll get back to you, aight?

hidden flicker
hidden flicker
indigo verge
#

The gist of it is, you'll never fix the weird jank with using raycasts to detect the ground, there will always be SOME kindnd of weirdness going on, so you have to use something eelse.

#

OH

#

I remember what it was.

indigo verge
#

so if you spawn the spherecast imagine there's a sphere that has to spawn, and if that spawn point's radius intersects anything, it ignores it during the cast.

#

I got around it like this:

    private void GroundCalcs()
    {
        belowMe = new Vector3(transform.position.x, transform.position.y - groundDetectRange, transform.position.z);

        aboveMe = new Vector3(transform.position.x, transform.position.y + 1f, transform.position.z);

        groundBelow = Physics.SphereCast(aboveMe, controller.radius, Vector3.down, out hit, groundDetectRange);

        //check if the player is on the ground.
        if (!groundBelow)
        {
            //if there isn't ground under the player, check if they were touching the ground last frame.  If they just now left the ground, set the gravity to zero, otherwise, increase their falling speed.
            if (!ground)
            {
                fallingSpeed = Mathf.MoveTowards(fallingSpeed, terminalVelocity, fallingAccel * Time.deltaTime);
            }
            else
            {
                fallingSpeed = 0f;
            }

            ground = false;

        }
        else
        {
            fallingSpeed = gravity;

            ground = true;
        }

        //add falling to the player's movement.
        direction.y -= fallingSpeed;
    }
#

Notice how I call the Spherecast ABOVE the player's root, THEN aim it down. this is to make sure when they're standing on the ground, the spherecast can never spawn intersecting it.

lean sail
indigo verge
heady iris
#

The problem with SphereCast is that it will ignore any colliders it starts inside of.

#

You can use OverlapSphere to check for any colliders that you're already overlapping

#

Although that's not going to give you a normal vector.

indigo verge
#

Yeah, and in my experience, that makes it finicky, even if you're using precise values. I know I'm biased, but you can't fathom how long it took me to finally get it working 100% consistently.

heady iris
#

But you could ask for the closest point on that collider and then use the vector from that to yourself as the normal vector, I suppose

#

My solution has to simply been to never have any slopes

#

I...should update my humanoid locomotion system

indigo verge
heady iris
#

I only recently added gravity. entities were bumping into each other and slowly floating into the air

#

eventually they detached from the navmesh and got confused

hidden flicker
#

Also, I'd like to just use the normal built in gravity.

indigo verge
#

IIRC, Spherecast can return the normal of the first surface it hit, let me look up the documentation

hidden flicker
#

Found it

indigo verge
#

Yeah, you should be able to use Spherecast to return the normal of what it hit.

#

Which would let you handle that nicely, I think!

heady iris
#

Yes. All of the various casts produce a RaycastHit.

lean sail
# hidden flicker Also, I'd like to just use the normal built in gravity.

when talking about player movement and slopes, "built in gravity" doesnt work. you wouldnt want your player sliding down every slope. Think about the case of running up and off the edge of a slope, players should just fall down immediately. Built in gravity will make it continue in its path while slowly falling down, like if you rolled a ball off a slope.

hidden flicker
lean sail
#

keeping vertical momentum sounds weird if these are supposed to be humanoid characters. Im not a major fan of toggling gravity on/off. Just keep it off and store what it currently should be

lean sail
hidden flicker
lean sail
#

Ok so you arent using built in gravity then if you are modifying it yourself

hidden flicker
#

It's... literally just modifying player velocity

lean sail
#

ive experimented around a lot and i found keeping track of gravity yourself is the most desireable. but 🤷‍♂️ do what you want i guess

#

no need to find work arounds and edge cases when you control what it is entirely.

rugged sail
#

how do I remove a sprite from a sprite sheet?

spring creek
rugged sail
#

i tried that

spring creek
rugged sail
#

o ok thx

chrome trail
#

There's a way to make the bool value in one script correspond to the bool value of another script using reference values, right? Because I have this function and it's not working

    {
        hitBuffer = inHitBuffer;
    }```

Tried doing the inverse and it's still not cooperating
spring creek
#

You are using it

#

Which means inHitBuffer is untouched

chrome trail
spring creek
chrome trail
spring creek
#

And this seems weird

#

Why do this at all?

chrome trail
spring creek
cosmic rain
spring creek
#

If you MUST, then have an event in the setter of a property
But I can't see a reason that you must

cosmic rain
#

You could have a reference type wrapper for your bool and change the bool in it, but I feel like you're trying to do something unreasonable.

sweet egret
#

Hey! I'm looking for some help with an error I'm getting when I followed the Samyam tutorial on making an online leaderboard. I followed all the steps thuroughly and it keeps giving me this error: Could anyone help with this? If they need any more information, please let me know!

cosmic rain
sweet egret
#

I believe so. VS wasn't telling me anything was wrong.

cosmic rain
#

It wouldn't tell that something is wrong, because it's a runtime error, not a compile error

#

You need to debug the value that you handle there at runtime.

sweet egret
#

oh ok. I should revise the code in the video. If i'm getting the same error, I'll check back and try that

#

Would there be something wrong with the parsing?

#

If it's an error with the string, the parse converts the int to string so I feel like that could be where it's coming from

cosmic rain
cosmic rain
sweet egret
#

Oh. didn't catch that

cosmic rain
#

That's what the error is saying too.

sweet egret
#

true. the video did cut to when she was using the parse so i don't think it's entirely required

#

I was wrong

sweet egret
#

parsing. I'm very new to this kind of thing

cosmic rain
#

You are doing it though

#

So obviously it's required by the tutorial

#

Int.Parse is parsing a string I to an int.

chrome trail
sweet egret
#

Agreed. there's not much going on in this script so in my eyes, there's not too much to work with in terms of finding the error

spring creek
cosmic rain
#

You should either add validation or make sure only valid string goes into it.

chrome trail
sweet egret
cosmic rain
sweet egret
#

thank you

spring creek
fervent furnace
#

The getter setter cause stack overflow

#

Your getter/ setter is calling itself

chrome trail
rain minnow
#

Use proper naming convention for the property to avoid that issue . . .

dense crow
#

i dont get any error but my i dont see the package in project tab

thin aurora
#

A coding channel is not any better. Please use the right channel, or just post it in #💻┃unity-talk

harsh sable
#

npm ERR! code ENDENT

Terminal (Ctrl+)

npm ERR! syscall open

DIE JG CONSOLE

npm ERR! path C:\Users\maqui\Downloads\JooBot-main\package.json

npm ERRI errno -4058

npm ERR! encent Could not read package.json: Error: ENDENT: no such file or directory, open 'C:\Users\maqul\Downloads\Joobot-main\package.json" npm ERR! encent This is related to nom not being able to find a file.

npm ERR! encent

npm ERR! A complete log of this run can be found in: C:\Users\maqui\AppData\Local\npm-cache\logs\2024-03-14T09_06_07_3032-debug-0.log PS C:\Users\maqui\Downloads\Joobot-main> npm

It says the package.json is nowhere to be seen

#

But its there

#

I see it myself

thin aurora
#

This channel is for general coding questions regarding Unity

opaque forge
#

Guys I have a question, I'm using a script to define the behaviour of my object (let's say object A) then I assign it to a gameobject in the editor, but now I would like to create a a new script that let's me create object A. Object A implements monobehaviour class, and has a start and update function, and I assign public variable some values to it in the editor. My question is now if I want to create a script that initiates object A, how should I proceed ?

#

I read that I would need to change it to a scriptable object and then could use a constructor, is that the best way to do it?

latent latch
#

Ah, sounds like composition approach so yeah SO is a good idea.

#
public class BaseObject : Monobehaviour 
{
  //fields

  public Assign(BaseObject_ScriptableObject SO)
  {
    //assign fields
  }

  //could also do a copy constructor, or instantiate and do the assignment all in one here
}

public class SpawnObject : Monobehaviour //could make this a singleton
{
  BaseObject baseObjectPrefab;
  
  public BaseObject InstantiateObject(BaseObject_ScriptableObject SO)
  {
    BaseObject newBaseobject = Instantiate(baseobjectPrefab);
    newBaseobject.Assign(SO);
    return newBaseobject;
  }
}```
#

Something like that?

thick terrace
lavish frigate
#

for good practice, would you guys recommend managing stuff like players stats (health, maxhealth, speed etc..) on the player itself, or make a managing singleton?

latent latch
#

i'd keep it on the player if the project is large enough, but you can always have references to the player via singleton

#

PartyManager.Instance.members[0] = first player of the party, ect

lavish frigate
#

Reason im asking is stuff like healthbars also need to know about player HP, so is a reference to healthmanager or playermanager better practice for example

latent latch
#

Depends how you're accessing it on the scene, but if you're doing colliders, you can just grab the stats directly from the mono

lavish frigate
#

Its colliders yeah

#

i guess ill just put a singleton playermanager mono on my player?

latent latch
#

Doesn't need to be part of the player's object, it can sit out anywhere in the scene as long as you bind the reference to the player's gameobject on it.

lavish frigate
#

Right, script will be the same for both ways tho so ill fuck around a bit and see

#

thanks

latent latch
#

ye, either way works really, I don't usually keep stats on the singleton personally, but I do keep references to the gameobject + stuff like input and camera

#

upgrades and stuff I could see being cached on a singleton manager

lavish frigate
abstract quartz
#

02n bvkmo,i4

#

0185,36kmno,lp ç.859460

#

15 c0724135,

lavish frigate
#

yep

placid crypt
#

wondering what the most up to date multiplayer networking system is, should i be using photon or NGO or something else?

vague radish
#

is there any issue with entities package with IL2CPP and unsafe code? bcs when i try use IL2CPP and unsafe code, unity reload and stop at updating scene for 1h and nothing happens

short gate
#

Guys idk anyting abt unity and i wanna do programming Where do i start

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

lavish frigate
#

Is there an easy way to figure out where one of these guys is coming from? cant double click

somber nacelle
#

that's an editor error, not likely related to your code at all. pretty common when the animator is open, but could be caused by any window that uses the graph view like shader graph

fossil shadow
#

Does anybody know if the crash logs stack trace has the deepest call on top or on bottom? On windows

#

As in, actual crash stack traces, not exceptions

elfin tree
#

How can I modify this ray code to ignore a layer, so that it does not block the raycast?


while (Input.GetMouseButton(0)) {
                var ray = mainCamera.ScreenPointToRay(Input.mousePosition);
                m_SpringJoint.transform.position = ray.GetPoint(distance);
                yield return null;
}```
#

I'm used to doing it with Physics.Raycast but that's pretty much it

fossil shadow
leaden ice
heady iris
#

I have a class (call it BaseClass<T>) with a generic type parameter. The parameter is used to give the class a field that holds its configuration data. So, FooClass<FooData> can have a FooData and BarClass<BarData> can have a BarData. In FooClass<FooData>, I can access data.someFooField.

BaseClass<T> is also responsible for setting up the configuration data.

This generic type parameter is "invisible" outside of the class. You cannot get a FooData out of a FooClass, and the type shows up on none of its public methods.

I want to be able to reference any BaseClass<T>, but since it's generic, that's impossible.

So far, my solution has been this mildly ugly hack: BaseClassImpl<T> derives BaseClass and defines the config data field. FooClass<FooData> and BarClass<BarData> thus derive from BaseClassImpl<T>.

I'm basically "covering up" the generic type with an intermediate class.

This works, but it's now causing problems.

I want to define a new class, SpecificClass, that has some extra functionality. However...

  • If I derive from BaseClass, I'm going to have to define a SpecificClassImpl<T> again, including the logic used to set up the config data.
  • If I derive from BaseClassImpl<T>, I'm back where I started: SpecificClass has a generic type parameter on it!

The alternative is to not have a generic type at all, and to just make FooClass and BarClass declare a field to hold their config data. They also have to set their config data up (fortunately, I can extract that into a static generic method that looks up the default data for them).

I'm not a huge fan of that because it requires duplicate code in every single class.

Any thoughts on this? I asked about this a few months ago, and I wound up going with this "covering up" strategy.

thick terrace
heady iris
thick terrace
#

why?

latent latch
#

if you can go with the field idea I'd go with that honestly

heady iris
# thick terrace why?
public class HearingConfig : Config
{
    public FloatConfigItem noiseFloor;
}

public class HearingConfigData : ConfigDataImpl<HearingConfig>
{
    public float NoiseFloor => GetFloat(config.noiseFloor);
}

the Hearing class has a HearingConfigData field, so it can access data.NoiseFloor.

GetFloat looks up a float value from a Dictionary<FloatConfigItem, float> to decide the current value (that's part of ConfigData)

#

The same "generic hiding" thing is going on here, since I want to be able to handle arbitrary ConfigData instances elsewhere

#

it's a conflict between:

  • I want specific classes to have easy access to their specific configuration data
  • I want to be able to make a big list of ConfigData so that I can serialize everything
#

HearingConfig is a scriptable object asset that everyone shares

#

HearingConfigData is a plain-old C# class that each instance of my Hearing class has (and which is populated with saved data)

#

FloatConfigItem stores things like the name and description of the configuration item, plus the default value, the increment for sliders, ...

thick terrace
#

what does ConfigDataImpl do with config?

heady iris
# thick terrace what does `ConfigDataImpl` do with `config`?
public class ConfigDataImpl<T> : ConfigData where T : Config
{
    protected T config;

    public void Setup(T config)
    {
        this.config = config;

        foreach (var item in config.items)
        {
            Init(item);
        }
    }

    public override Config Config => config;
}

It needs the Config object so that it can iterate over every ConfigItem and set itself up with default values.

heady iris
#

The alternative would be to directly give the Hearing class that FloatConfigItem, and to have it directly call GetFloat on its ConfigData.

#

Then there'd be no need for generics at all here.

#

I'd just do float noiseFloor = myData.GetFloat(noiseFloorConfigItem);

thick terrace
#

i think if you can avoid it, that would make things a lot simpler

heady iris
thick terrace
#

i was thinking if you get rid of the config field in the base class it'd make things simpler too, you could still have Config as an abstract property if you need it

heady iris
#

that's true (and I've done something similar in several places)

thick terrace
#

but all the generic param is doing really is changing the type of field it's stored in, so making each subclass declare the field itself is basically the same thing

heady iris
#

I could give HearingConfigData a HearingConfig config field and then override that abstract property.

thick terrace
#

yeah, exactly

heady iris
#

It's the same problem in two different places.

#

I don't like the code duplication, but the generic class is creating a lot of ugly code too

#

plus the cognitive load of having Foo and FooImpl and generic type parameters flying everywhere

#
private HearingConfigData data;

public override void Init()
{
    ConfigDataMaker.Get<HearingConfigData, HearingConfig>(out data);
}

god i wish it could infer that generic type parameter for me

heady iris
#
public abstract class ConfigurableModule<TConfigData,TConfig> : Module where TConfigData : ConfigDataImpl<TConfig>, new() where TConfig : Config
{
    protected TConfigData data;
    [SerializeField] SerializedConfigData defaultConfig;

    public override void Init()
    {
        data = new();
        data.Setup(OwnConfig);
        data.Read(defaultConfig);
    }
latent latch
#

oh no

heady iris
#

(this would be SpecificClass in the original example)

#

it's got TWO type parameters!

wicked scroll
#

maybe what you really want is dynamic hides

heady iris
#

Thanks for the help! I need to go stare at this some more, but I'm a lot less married to this funny "covered up generics" idea now

thick terrace
#

it's basically down to where you want to draw the line in your hierarchy where you declare the concrete type, and everything above that needs to be various levels of generics

latent latch
#

ive set my own personal constraints to only ever using a single generic parameter (utility scripts are a different story though)

heady iris
#

So it'd make more sense to have each derived class declare its own field and provide access to it through a property

#

no more generic parent type

chilly surge
#

What about an IBaseClass? Since none of your public API surface cares about the generic which is an implementation detail.

heady iris
#

But Setup only needs that because it's writing it to a TConfig field.

#

So when that field goes away, Setup can accept any Config

#

and now ConfigurableModule only needs the generic type parameters for its own data field

#

and when that goes away, nobody needs generics anymore at all

#

a few extra lines of code per module class is worth not having...this mess

chrome trail
#

Is there a reason this collision might not register even when both colliders are most definitely active and the collision between the two layers they're on is also supposed to be active?

leaden ice
next salmon
#

Do they have rbs?

chrome trail
#

Well, the weapon doesn't have a rigidbody. I mean both capsules do have one

magic wolf
#

Hey guys quick question. Please @ me when you answer. When you have a physics2d.raycast if you filter by layer and will it bypass through other lays searching for that layer or does it stop at the first thing it hits then return false if not of the proper layer.

leaden ice
#

as if it's not there at all

#

it will only hit things in the layer mask

magic wolf
#

Ok thank you

hard viper
#

also, anything outside the layer mask doesn’t affect performance

#

if you raycast into 1000 colliders, that might take 1000 units of time. But if you filter by a layer mask that only includes 10 of them, it would take 10 units of time.

#

roughly speaking

leaden ice
hard viper
#

i did testing with Physics2D. All the queries I checked behaved like that

#

idk if that also applies to 3D

leaden ice
#

They are different engines

#

it's not necessarily the same

#

Box2D vs PhysX

#

I wouldn't be surprised if it's true, just not a guarantee

hard viper
#

in this case it was raycast2D

leaden ice
#

oh true

hard viper
#

i can make no guarantees about 3D

#

the 3D engine does a lot of things differently. Just with a slightly similar sort of API

#

because it’s all unity (which deals with components).

magic wolf
vapid bluff
#

Hello

#

I added a menu scene, with 3 buttons (play, options and exit)

#

I made the script for the buttons, but they don't work

#

I even specify wich scene should load when I press play

harsh root
rigid island
rigid island
magic wolf
#

@leaden ice here is everything

#

if there is anything I am missing let me know

#

like anything you needs SC of

rigid island
#

embeds aren't working rn

leaden ice
#

the images aren't working yeah 😦

magic wolf
#

oh dang...

leaden ice
#

maybe find a hosting site and link them?

magic wolf
#

Can I DM them?

leaden ice
#

I don't think it'd help

#

if discord is having an issue

magic wolf
#

ok one sec

#

Does that link work?

leaden ice
#

yes

magic wolf
#

ok

#

Now I assume is where you point out a super obvious mistake XD

leaden ice
#

Things look ok at first glance but it's hard to say exactly where the raycast is

#

turn gizmos on!

magic wolf
#

gizmos??

chrome trail
magic wolf
#

Im semi new to unity whats gizmos?

leaden ice
#

Then you can see your Debug.DrawRay

#

Your DrawRay isn't correct though

#
Debug.DrawRay(new Vector2(transform.position.x, transform.position.y - (playerCollider.size.y * transform.localScale.y / 3)), -transform.up, Color.red, 0.05f);```
It should be this:
```cs
Debug.DrawRay(new Vector2(transform.position.x, transform.position.y - (playerCollider.size.y * transform.localScale.y / 3)), -transform.up * 0.05, Color.red);```
magic wolf
#

oh color is after?

leaden ice
#

the last param is time

#

it displays for that long

#

the distance and direction are combined in the second param

magic wolf
#

I turned gizmos on. the. the ray is spot on.. now I am more confused..

#

pic is in same link

leaden ice
#

try again after the change I suggested to the DrawRay

#

I don't think the ray is long enough

magic wolf
#

Yep. too small

#

Ill try changing size. one sec

ocean blade
#

I'm making a gun right now, coding the recoil system. I want the rotation of the gun to kind of "overshoot" when lerping to the desired rotation.
Like, it goes over the target rotation, if it started from 0 to 90, it goes a bit over that. I've tried and got... something. It's just a mess and I'd be embarrassed to show it, but if I must, I'd gladly do it then.

rigid island
ocean blade
mossy wind
#

For collision detections, do I need to have both Rigidbody 2D and Collider 2D on the gameobject?

leaden ice
chrome trail
ocean blade
mossy wind
chrome trail
#

Is the rigidbody on the bullet's collision detection property something other than "discrete"?

rigid island
#

integers are max exclusive

ocean blade
mossy wind
chrome trail
mossy wind
#

On both objects?

chrome trail
mossy wind
#

Nope, that didn't fix it

rigid island
#

Translation for example will not give you accurate result

mossy wind
#

Upon instantiation, I assign a constant velocity to the bullet's Rigidbody component

leaden ice
#

Anyway is the bullet visibly colliding with the enemy?

#

If it is, it's not a tunneling problem

mossy wind
leaden ice
#

Just try adding it, you can make it kinematic

night storm
#

i think even if u use the correct rigidbody moving method and have it set to continous then very fast moving small objects can still pass through walls and stuff for some reason... idk why and idk how to fix that

rigid island
#

unless we're talking speeds over 1000 units

grave tundra
#

I am making scenes at Runtime. When I do SceneManager.CreateScene - it only does it additive. Anyone know why? Anyone know how to fix that? I still only want the new scene active.

mossy wind
#

I did not understand the tunneling thing, but I checked both z coordinates and it's 0

leaden ice
#

sounds like it's going right through

#

can you show screenshots of your setup?

mossy wind
#

Oh you mean colliding as in hitting and changing direction, velocity, etc.?

leaden ice
#

yes

mossy wind
#

Yeah that's not happening

leaden ice
#

then it's not colliding at all

#

show screenshots of your setup

#

Especially showing the components on each object

mossy wind
#

Bullet (I tried both Discrete and Continuous for collision detection):

#

Enemy:

#

If, for whatever reason, the shape of the bullet may influence this, this is what it looks like:

vapid bluff
# rigid island show current code then
public class mainMenu : MonoBehaviour
{
    public void playGame ()
    {
        SceneManager.LoadSceneAsync("Level 1");
    }

    public void quit()
    {
        Debug.Log("Quit!!!");
        Application.Quit();
    }
}
#

I tried with index, with (1) as the next index and nothing

rigid island
vapid bluff
#

yes

#

not working

rigid island
vapid bluff
#

what?

rigid island
#

You said the buttons work but the script don't work

simple egret
#

Tbf the original question is very weirdly formatted

#

With the "how" as the last word

vapid bluff
#

my bad

#

I wasn't reading all of it

rigid island
vapid bluff
rigid island
vapid bluff
#

yes

rigid island
#

did you try the actual LoadScene method

simple egret
rigid island
#

Yeah my English skills are very basic :\

#

I see what you mean though

vapid bluff
#

dw

rigid island
# vapid bluff yes

LoadSceneAsync is async so its running in the background, maybe its loading and you're not noticing and you keep pressing ?

simple egret
#

Nah they're very far from basic lol, I've seen wayyy worse here

rigid island
#

gotta practice more 😅 been in US 10 year

simple egret
#

Also, The Obvious™️, have you added your scene to the Build Settings list?

rigid island
#

put Debug.Log in playGame method

#

make sure the method itself runs

simple egret
#

Try specifying the index instead of a string if you haven't done so yet. Strings are much more error-prone, like you can add a space at the end by mistake and not notice it, but I guess you'd get an error about the nonexistent scene at this point

vapid bluff
#

nevermind

rigid island
#

fixed?

vapid bluff
#

I put the script in the Onclick function and it didn't saved

vapid bluff
rigid island
vapid bluff
#

I just hate when I put things and they don't save even if I press the save buton

rigid island
#

the scene should save, but its not saved if you have *

vapid bluff
#

true

#

well, I made it sure it will stay saved

mossy wind
#

@leaden ice @rigid island It seems like Kinematic and Kinematic collision doesn't work for some reason, when I changed it to a trigger and modified the method it worked. Just thought I'd let you know 👍🏼

leaden ice
#

it's not going to collide with stuff

rigid island
#

how are you setting velocity on kinematic 🤔

leaden ice
rigid island
#

Ahh 2D

leaden ice
#

sorry I was out on a walk

#

so I didn't see the initial response

leaden ice
mossy wind
#

Should I set to dynamic and set gravity scale to zero?

leaden ice
#

kinematic turns it into an unstoppable object that's not affected by anything else

merry stream
#

what are the pros and cons of utilizing a multi scene workflow with ui, gameplay, etc on seperate scenes vs just having everything in one scene?

#

im failing to see the purpose of complicating everything by having to use a service locator or something like that to easily talk between scenes

merry stream
#

elaborate please

rigid island
#

some projects it makes more sense to have multiple scenes, especially when the map is big and you need to work with multiple people

#

multi-scene setup allows everyone to work on their section of the map without creating Merge conflicts on Version Control for example

merry stream
#

im not talking about having seperate scenes for each map

rigid island
#

Loading entire map is more costly then splitting to Multiscenes loading (look at firewatch does this well)

leaden ice
merry stream
#

im talking about having each element in its own scene, like having a bootstrapper scene which holds your save system etc, then having a ui scene, then having the actual "map" scene

leaden ice
#

but I guess an advantage in general is that the more scenes you use, the less VCS conflicts you have to deal with

merry stream
rigid island
leaden ice
merry stream
#

something like this

#

UI as in inventory, health

rigid island
#

why not just prefabs with DDOL

merry stream
#

i know, thats why im questioning if it's worth it to setup something like this

heady iris
#

I've tried a separate menu scene before. It's a lot of extra hassle to handle the loading and unloading.

#

I did not see a very obvious benefit

merry stream
#

this is the video im questioning https://www.youtube.com/watch?v=JFP-cCFID7o

Learn how to load multiple scenes asynchronously and additively, at the same time in Unity, with plenty of customization and a load screen. Load and Unload multiple scenes at the same time with less overhead and continuous progress reports!

Want to support me? 😀
Buy me a coffee! https://ko-fi.com/adammyhre

🔔 Subscribe for more Unity Tutorials...

▶ Play video
rigid island
#

yeah to me just seems more work than its worth

merry stream
#

how do you recommend handling scene loading?

#

like what do you typically do

swift falcon
#

someone please show me a script code for 2d movements

rigid island
#

like the PlayerUI for me is a prefab canvas that spawns with the player so I can put player anywhere it always has UI

heady iris
#

the current game I'm working on leans towards a single scene (individual levels)

#

so my menu UI just lives in DontDestroyOnLoad

lean sail
#

Single scenes is definitely a lot easier

rigid island
#

but other projects I have like for pre-made levels , I cannot have one scene for that multi-level single scenes make sense

#

but not not singletons or any logic

merry stream
#

agreed, i don't see the purpose of complicating things like shown in the video

#

theres a weird gap in unity tutorials where most are terrible and way too basic then the rest are way overcomplicated

rigid island
#

yes very overlooked concept in any development is KISS

#

Keep it Simple Stupid

merry stream
#

the youtuber i posted has a lot of very interesting videos but I feel like you can accomplish the same thing with way less overcomplication, but maybe im being naive

grave tundra
#

Can I somehow set or get/modify LIghtingSettings at runtime?

heady iris
#

so I had lots of additive scene loading already

rigid island
#

mostly yes

rigid island
#

there are hundreds of scripts

grave tundra
#

I mean, at a bare minimum how can I load A LightingSettings asset and assign it to the scene? Docs imply its only in UnityEditor

swift falcon
#

💀

#

i need basics

rigid island
heady iris
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

rigid island
swift falcon
#

yea

rigid island
#

otherwise you're just blindly copying, if something breaks you're screwed

grave tundra
#

Maybe hop on over to #💻┃code-beginner, but honestly, there are THOUSANDS of blogs, videos, classes on Unity basics, including 2d character animation, movement, and collision.

rigid island
grave tundra
#

Sometimes Unity just isn't built for that 😄

rigid island
#

hmm you mean like bake lighting you prob need realtime lights etc

grave tundra
#

I'm not doing any baked lighting

rigid island
#

idk thats more challenging to optimize generated scenes. I dont know much about runtime gen

arctic plume
#

Does anyone know what's wrong with this code?

    public void playAnimation(Animator animator, float animation, string parameter)
    {
        animator.SetTrigger("look");
        StartCoroutine(Animating(animator));
    }

    private IEnumerator Animating(Animator animator)
    {
        while (animator.GetCurrentAnimatorStateInfo(0).IsName("look"))
        {
            Debug.Log("Waiting");
            yield return null;
        }
        speaking = false;
        Debug.Log(animator + " is done doing a non-speaking animation.");
        currentSpeaker = null;
    }

My code never goes into the while loop but it plays the animation state fine in the scene

rigid island
#

eg the whole static batching

heady iris
grave tundra
#

Yes, but I can't assign a LightingSettings object to a scene.

rigid island
heady iris
#

ah, the example uses Lightmapping

#

which is indeed editor-only

grave tundra
#

Exunchtly 😄

rigid island
#

I would store the bool inside update instead then check in while loop @arctic plume

#
Update()
...
isLookAnimation = animator.GetCurrentAnimatorStateInfo(0).IsName("look");
...
IEnumerator Method()
...
while(isLookAnimation )
//etc
...```
heady iris
#

this contains the Environment settings

#

as opposed to the settings used when baking lightmaps

#

I forget how you actually access the current RenderSettings, though..

grave tundra
#

Most is static I think

heady iris
#

oh, duh

#

I guess it just gives you the settings for the active scene?

#

Note that render settings are per-scene.

grave tundra
#

RenderSettings.skybox = material; works for my skybox builder

#

Right, I assume its all the active scene that you're setting (which is odd AF... )

heady iris
#

well, the Environment settings are global, so I guess you can only use one scene's settings at a time anyway

arctic plume
rigid island
#

did you try what I sent?
its possible by the time the coroutine while loop hits the IsName is false

grave tundra
heady iris
rigid island
grave tundra
#

I'm doing a lot of procedural generation, so I was attempting to build scenes 100% from code and no editor interaction or prefabs

midnight hemlock
#

hi
does anyone knows why vector3 doesnt show up in inspector ?

`[SerializeField]`

public Vector3 pos;

leaden ice
#

You only need public OR SerializeField not both. Your error is elsewhere

grave tundra
#

Can you have that show in inspector? I thought you need a custom editor gui for v3

heady iris
#

Vector3? no

heady iris
midnight hemlock
heady iris
heady iris
#

you're using System.Numerics

leaden ice
heady iris
#

get rid of that using directive and replace it with using UnityEngine;

grave tundra
#

Yeah that makes sense, but it seems absolutely absurd that its a static... why does unity make these weird mistakes? What if I have two scenes loaded?

heady iris
grave tundra
#

Even with stacked scenes? Only the active's apply?

midnight hemlock
heady iris
#

!code

tawny elkBOT
heady iris
#

The HDRP moves a lot of stuff out of RenderSettings and into the Volume framework

#

but I believe the built in RP and the URP both keep a lot of stuff in RenderSettings

grave tundra
#

Yeah I'm using URP

compact linden
#

Hi, I'm trying to setup couch coop with different playerinput components for different players and having a problem when it comes to rebinding. When I try to rebind using the RebindingUIPrefab asset the new input system comes with, only the first User gets it's action rebound. This is even weirder when you consider the fact that the first User isn't even using the correct control scheme the binding im trying to rebind has. How should I go about fixing this issue?

Image 1: Shows that the wrong user is getting rebinds. (Controls get disabled while rebinding.)
Image 2: How I set up the PlayerInputs. Each object there has their own PlayerInput Component.
Image 3: Shows how the control im trying to rebind doesn't exist on the Keyboard2 control scheme even though it is getting rebound in the PlayerInput component that's setup to be in Keyboard2 control scheme.

arctic plume
#

I don't get why it never is true, if I clearly see it happening in the scene

rigid island
arctic plume
#

You want a picture of the animator sheet?

rigid island
midnight hemlock
#

@leaden ice Thank you for your help , as it turned out, I had a custom editor for this script and completely forgotten about it lol

arctic plume
rigid island
#

an easier way would probably be to just use an Animation event

arctic plume
#

What's an animation event?

spice briar
#

hey everyone, im trying to make a gizmo line that follows multiple vector3 points

#

essentally every update, im putting the position of the bullet into a list and i want to display those points as a line

#

ive tried using Gizmos.DrawListLine(), but it doesnt work
it says "Each pair of points from the points span represents the start and end of each line, so Unity draws the first line from points[0] to points[1], the next from points[2] to points[3], and so on." So essentially, i have an odd number of points in my array

#

but i dont want it to go [0] to [1] then [2] to [3], i want it to go [0] to [1] to [2] etc.

grave tundra
#

then add each vertex twice?

spice briar
#

then it would go from 0 to 0 then from 1 to 1

#

i guess i could re-add every odd index

grave tundra
#

0,1,1,2,2,3,3,0 would make a loop

#

Maybe also check out Gizmos.DrawLineStrip

spice briar
#

wait, just looked on the unity docs and Gizmos.DrawLineStrip is exactly what i need

#

yepp lol

lean sail
spice briar
#

just editor, i have line renderer tracers for gameplay

indigo verge
#

What are the downsides of using ObservableList vs using just List? ObservableLists almost sound too good to be true, for when you need to react to changes in a list.

hard viper
#

if you don’t need to invoke anything, it is strictly inferior to a list

stoic mural
#

But it works still

indigo verge
#

I can't find any documentation explaining how exactly to use an ObservableList to trigger a method.

#

Does anyone here know where to point me in the right direction?

#

So far, the ONLY thing I've been able to find is not Unity's inbuilt ObservableList, but what seem to be people's custom implementations of it?

leaden ice
#

Skip the whole angle calculation entirely

indigo verge
# leaden ice The docs have the events in them

YEah, what I'm struggling with is figuring out how to USE them, I've tried making it like I did my otheer event handler, but ssomething is differnt about the syntax or something, and I can't find any information on what I'm doing wrong.

I'm trying to add listeners for the event, but no matter what I try or look up, it just throws syntax errors.

lean sail
#

You should be able to get your IDE to autocomplete a method for it tbh

indigo verge
#

I'm trying to figure out how delegates work now, but the syntax and formatting for the documentation on those is ALSO different and isn't helping me figure out what to do.

#
    public delegate void ListChangedEventHandler<T>(ObservableList<InventorySlot> sender, ListChangedEventArgs<InventorySlot> e);

I have this, but I have literally no clue what it does, or how it works, and what I've been looking up to try and explain it to me is talking about stuff utterly unlike this.

stoic mural
indigo verge
#

I absolutely cannot get my IDE to tell me what the heck it wants.

lean sail
indigo verge
#

Reading the documentation hasn't helped me figure out what needs to happen for that. Googling hasn't found anything on it

lean sail
indigo verge
#

I am using Microsoft Visual Studeo

#

I don't know what it WANTS from me to make it work though!

lean sail
#

do you not see anything when you try to subscribe to the delegate?

#

which inserts

    void Awake()
    {
        oList.ItemAdded += OList_ItemAdded;
    }

    private void OList_ItemAdded(ObservableList<int> sender, ListChangedEventArgs<int> e)
    {
        throw new System.NotImplementedException();
    }
#

my test list was using ints so thats why its <int>

indigo verge
#

So wait, what is the difference between that and AddListener? Because I've only seen this thing done with AddListener.

lean sail
#

that is for unity events, this is a c# event

indigo verge
#

Christ. Alright. Thank you very much for the help. I'll try that.

lean sail
#

+= is a bit of syntatic sugar for what its really doing, but this is how you subscribe to a delegate

ruby nacelle
#

Hey I'm just wondering how I can avoid instances resetting themselves on level reload, the logic is proper, but for whatever reason if I start with an instance, load a new level and then return to the first level, the instance is null and wipes any data contained

#
    private static PlayerWallet _instance;
    public int amountToPutInWallet; // Used to accumulate daily earnings
    public int walletAmount; 
    public delegate void WalletAmountChanged();
    public event WalletAmountChanged OnWalletAmountChanged;

    public static PlayerWallet Instance
    {
        get { return _instance; }
    }

private void Awake()
{
    Debug.Log($"[PlayerWallet] Awake called. Current instance: {_instance}, Current amount: {walletAmount}", this);

    if (_instance != null && _instance != this)
    {
        Debug.Log("[PlayerWallet] Duplicate instance detected, destroying this one.", this);
        Destroy(gameObject);
    }
    else
    {
        _instance = this;
        DontDestroyOnLoad(gameObject);
        Debug.Log("[PlayerWallet] Instance assigned and set to DontDestroyOnLoad.", this);
    }
}```
lean sail
dusk apex
ruby nacelle
#

Here's an example of it in engine

#

On reload of the level it's detecting the instance as null

#

How should I re-write the logic of the DDOL, I've also tested it with other scenes, it transitions makes a new instance and then properly tracks

#

It's specifically only occuring if I bounce back to scene 1 instead of going to a scene 3

dusk apex
#

Are you destroying the instance prior to changing the scene or anywhere?

#

A ddol object won't be destroyed unless explicitly

ruby nacelle
#

I don't believe so, should I destroy the instance when it goes to change days?

dusk apex
#

If you are getting null, you've destroyed and created the instance again.

ruby nacelle
#

It's so weird, because I never explicitly destroy it when moving between scenes

dusk apex
#

I suggest looking at your code where you are returning to scene one instead of three.

ruby nacelle
#
    public void NewDay()
    {
        //Increase the day counter
        SO_Data_dayCycle.currentDay++;
        currentDay = SO_Data_dayCycle.currentDay;

        //Update Grass Tiles
        SO_Data_dayCycle.grassTilesList = new bool[grassTiles.Length];

        RandomizeGrassRegrowth();

        PlayerWallet.Instance.PutValueInWallet(PlayerWallet.Instance.amountToPutInWallet, "End of Day");

        //Saving cut data into the scriptable object
        for (int i = 0; i < SO_Data_dayCycle.grassTilesList.Length; i++)
        {
            SO_Data_dayCycle.grassTilesList[i] = grassTiles[i].m_IsCut;
        }


        SceneManager.LoadScene("EndOfDayScene");
    }```

Is instance one, I debugged it, the value doesn't change
End of day literally just loads the scene
```cs

    IEnumerator ResultsAnimation()
    {
        //lop through vertical layout group children and set animation to middle of screen

        foreach(GameObject panel in rewardPanels) 
        {
            LeanTween.moveX(panel, verticalLayoutGroupGO.transform.position.x, 1).setEaseOutBack();
            yield return new WaitForSeconds(0.5f);
        }

        yield return new WaitForSeconds(1);

        SceneManager.LoadScene(sceneToTransitionTo);
    }```
dusk apex
#

Nothing seems wrong with your Singleton Awake method. You've likely explicitly destroyed the Singleton instance elsewhere.

ruby nacelle
#

Should I just remove the singleton from the heriarchy and instantiate a copy of it on first load? do you think that would help?

dusk apex
#

Not sure how that would make any difference. Awake would occur and if there were or weren't any instances, the effects would resolve

spice briar
#

If the Scene is loaded again, Unity loads the script instance again and calls Awake again.

#

you may need to add DontDestroyOnLoad(gameObject);

dusk apex
#

Pretty sure that was in the else

spice briar
#

oh

dusk apex
spice briar
#
    void Awake()
    {
        if (instance == null)
            instance = this;
        else
            Destroy(gameObject);

        DontDestroyOnLoad(gameObject);
    }```
heres how i do singletons usually
wintry crescent
#

Is there any preformance penality when firing a UnityEvent with a lot of calls on it? Assuming said calls aren't very expensive on their own, I'm talking specifically the UnityEvent part
say, there's a couple of hundred of objects, all registered to a single unityevent, that can fire like once/twice a second at most

dusk apex
#

If the instance isn't null and it isn't this (it'll never be unless you've assigned it prior to this line), destroy this object. Else assigned the instance to this and flag it to not be destroyed implicitly.

dusk apex
spice briar
#

yeah

dusk apex
#

It's likely getting explicitly destroyed somewhere when going from scene 2 to 1 where going from scene 2 to 3 is fine.

mossy snow
#

it's being destroyed because it's not DDOL. He's turned off warnings in the console, so he's not seeing the warning where it says DDOL is only valid for root GOs which his wallet manager is not

spice briar
#

im just wondering because if the instance exists, and is not this, then it destroys the gameObject

dusk apex
dusk apex
lament cove
ruby nacelle
#

We were using empty game objects to organize the heirarchy

#

lmao

past barn
lament cove
indigo verge
#

That tears it. I just found out that ObservableLists cannot be displayed in editor. I'm switching back to normal lists and just making my own events for it.

past barn
# indigo verge That tears it. I just found out that ObservableLists cannot be displayed in edi...

If you use Odin, you may be able to utilize something like this:
https://odininspector.com/attributes/on-collection-changed-attribute

indigo verge
#

So, a dictionary can create pairs, but what happens when one part of the pair is removed?

Dictionary<myList, GameObject>

For example, if I were to remove myList[1], what would happen to the dictionary entry which contains that?

#

I'm wanting to remove dictionary entries when their associated list is gone, but I'm unsure what happens to dictionary entries who have had one of their pairs removed.

dusk apex
#

How are you implementing the removing of they key without removing the value?

indigo verge
#

I'm doing myList.Remove(index), I'm wondering what happens to the dictionary when that happens.

dusk apex
indigo verge
#

Ahh, that's... Hmm.

dusk apex
#

Modifying the elements of the list shouldn't effect the key/value pair

indigo verge
#

so basically, the key isn't the contents of myList[i], but that specific index?

#

So if i removed an entry from the list, the new entries that occupy its former index would become the new pair to the former pair's gameobject???

dusk apex
heady iris
#

modifying the list would therefore not mess up the dictionary

indigo verge
#

So if you remove one, it removes the other, functionally?

heady iris
#

Remove one what?

#

If you have a Dictionary<List<int>, GameObject>, then removing an item from one of the lists that's being used as a key will do nothing.

#

The dictionary cares about which list is which, not about the exact contents of the lists.

quaint rock
#

list would be by indentity

#

what is the purpose of the list key, is there a fixed set of items in it?

#

Lists as keys feels really weird too me, like its not he best thing for a key, and sounds like you might jsut want a list of structs or tuples

fervent furnace
#

If you didnt override the gethashcode then your dictionary is useless (you must have the same instance to retrieve the value)
If you override it and it returns value based on the element, then your dictionary wont work after you modify the key

#

Ofc you can store all the keys in some collections

#

But in this case then you will need another “key” to access specific list so you can just create a dictionary<another key,gameobject>

stone ginkgo
#

soo i need to access a variable from another script but the variable is also in another class within that script, and the class name is not the same as the script name, so how would i write that?

spring creek
#

I'm a bit confused. You want to add Status_Burn to a list. And is there an error?

prime flax
#

There is no error its just when i add it to the list it just adds a None status effect i can send a ss

spring creek
#

Or is it that you want to access stuff from the child when you iterate the list? That won't work

prime flax
#

What could i do instead then

prime flax
#
[SerializeField] public List<StatusEffect> statusEffects;

that is the list i made and ive got it serialized so i can show you a ss of the inspector aswell

spring creek
# prime flax What could i do instead then

You could put some method on the parent that the child OVERRIDES. Then the child would just change the behaviour, but you don't need access to anything other than the parent.

#

Yeah, send the ss

prime flax
#

thats it added onto the entity

spring creek
#

Can you show the code for the list?

#

The Manager, right?

prime flax
#

thats the script that has the list defined

#

and lemme get u the manager

cosmic rain
#

!code

tawny elkBOT
prime flax
#
public class StatusEffectManager : MonoBehaviour
{

    public delegate void StatusEffectEventHandler();
    public event StatusEffectEventHandler StatusEffectEvent;

    private void Start()
    {
        InvokeRepeating("InvokeStatusEffectEvent", 0f, .5f);
    }

    public void InvokeStatusEffectEvent()
    {
        StatusEffectEvent?.Invoke();
    }
}
#

dont mind comments i used to have a different way i handled status effects but i didnt like it

#

it worked but it wasnt efficent and the way i liked it

#

so basically i just wanted to have a list of status effects under a entity that i can add to and remove from. then i would have a invokerepeating to trigger it every half a second to apply its effect

#

I have another system in my game just like it but it isnt a list on a script its monobehaviours put on the entity itself so its quite different

spring creek
#

I had to hop on my computer to look at the code. But just on a quick look, I don't see where you initialize the list

prime flax
#

its in entity stats

#

at the top

spring creek
#

But that is not an initialization

#

Maybe I'm missing something?

prime flax
#

oh my fault i read it wrong lemme show u rq

#
public class Card_FireAffinity : MonoBehaviour
{
    EntityStats playerStats;

    private void Awake()
    {
        gameObject.GetComponent<EntityStats>().OnHitProjectileEvent += this.OnHitProjectile;
    }
    private void OnHitProjectile(ref AttackInfo attackInfo)
    {
        FireAffinity(ref attackInfo);
    }
    void FireAffinity(ref AttackInfo attackInfo)
    {
        if (Random.Range(1, 101) < 99)
            attackInfo.Victim.GetComponent<EntityStats>().AddStatusEffect(new Status_Burn(attackInfo.Victim, 5, 1));
    }
}
#

fireaffinity method

#

i thought u meant declaration originally

spring creek
#

There is no initialization here either

#

something like statusEffects = new List<StatusEffect>()

lean sail
#

Unity initializes it since its public

prime flax
#

yea

#

its a empty list

#

then i try to add to it

spring creek
rigid island
#

works with SerializeField too

lean sail
#

Do these scripts need to be monobehaviour? Could be a lot simpler if they were like SO or something

rigid island
#

basically any time unity serializes it

prime flax
#

I can make them monobehaiours and put them on the object but im already doing something like that and I dont really wanna have a million different scripts under 1 object

#

i dont know how that would effect performance but it just felt wrong to do

spring creek
#

are they NOT on objects?

prime flax
#

no they are not infact

#

would that be a problem

spring creek
#

Yeah

prime flax
#

can i not just have a list of them

#

without them being on a object?

spring creek
#

I don't think so, someone should confirm that though

rigid island
#

you can

spring creek
#

why not just remove the MonoBehaviour part

#

oh dang. Wrong again

prime flax
rigid island
#

but yeah SOs would make more sense

prime flax
#

ig but other than that any reason its not working

spring creek
prime flax
#

like im willing to change the way im willing to do this but im really curious why i cant have it the way it is rn

rigid island
#

say you want a random ability placed on enemy etc.

spring creek
#

That could be cool too

rigid island
#

but yeah at that point you mind as well SOs which basically do that, but the benefit is MB has more Unity Events methods built in

prime flax
#

if i used SOs how would i have seperate functionality per status effect

#

i dont want to do a fat switch case