#archived-code-general

1 messages · Page 247 of 1

clear oriole
#

The goto statement can lead to code that is difficult to read, understand, and maintain

calm talon
#

I am such an idiot

#

that's why the code no work lol

shell scarab
#

I'm writing a light level gen script for a prototype. In the first part of the while loop I basically set up some variables I need. In the second half I use a random instance to get up down left or right, but up down left or right may be taken, so I basically just say if right is already generated but I know that some combination of up, down, left or right is open for the current cell, goto the line where a random direction is gotten instead of restarting the loop and regenerating all the variables I need (which were already generated and would generate to the same value if restarted).

clear oriole
#

also the goto can introduce potential bugs and errors as it allows for non linear program flow which can make it difficult to reason about the state of the program at different points its just not great to use "All the time" but i mean once or twice i dont see why not

shell scarab
#

idk, goto seems stigmatized. It's still pretty linear unless you have gotos stringed together.

clear oriole
#

Well sure the goto is linear but it makes other code not linear

calm talon
shell scarab
#

i mean, only if you use it like that. I've only really seen cases to use it when you absolutely need to break out of multiple loops with it, or when you want to repeat only part of a method but it would be unreasonable to move that part into its own method or local method.

clear oriole
#

it just makes the code less structered really and when you start getting lots of scripts it can build up really fast and it can just cause a lot of issues down the road but its not a terrible thing to use, just has to be controlled

shell scarab
#

well I get what you're trying to say I think, but what issues?

#

I mean anything can cause issues down the road.

clear oriole
#

well it creates spaghetti code which makes readability pretty hard which is where the control part has to come in, and the go to statement can cause many unintended bugs and debugging go to statements can present more of a challenge especially without proper commentation and jumping to different parts of code like that might cause values to not be correct depending in the circumstance, and the go to statement may not be supported on other platforms.

#

But to be fair everything comes with its list of issues

#

Im only fimiliar with windows and mac so i couldn't tell you what platforms but there are things like that, that wont work on mobile devices

#

Idk if possible i would find a better alternative to your problem if possible if all else fails screw it

somber nacelle
#

#archived-networking
also the only answer worth anything is "do your own research and determine which networking solution best fits the needs of your project"

#

also DOTS is not networking

nimble cairn
#

Is GameObject.CompareTag("x") == "x" still better to use than gameObject.tag == "x" in 2024?

somber nacelle
#

the CompareTag method is always going to be better than string equality. also it's just gameObject.CompareTag("x") not gameObject.CompareTag("x") == "x"

nimble cairn
#

Yep!

#

Thanks

#

@somber nacelle What about in this instance.

Do you see any room for improvement?

#

Surely this is better, having a bit of GC once than all the overhead of compare tag multiple times

quartz folio
#
  1. local variables should not be prefixed with underscores
  2. why's the highlighting so bad? Is VS Code actually configured?
  3. you can get transforms directly from components, you don't need to go through the gameObject
  4. bridgeParent should just be a Transform if that's what you care about, unless you use it for GameObject-specific things, just use the type you care about
somber nacelle
quartz folio
#

But yes, that is probably on par with CompareTag, but it avoids any warnings CompareTag gives when you're missing a tag

nimble cairn
#

@quartz folio

  1. I know, however in this instance I prefer the underscore.
  2. My configuration is fine -- omnisharp is not running so I could take a quick screenshot.
  3. Can you elaborate?
  4. I've experimented with both Transform and GameObject and GO is just easier for this method.
quartz folio
#
- col.collider.gameObject.transform;
+ col.collider.transform;
#

Ah I was wrong on 4, you declare it right there. I thought it was a serialized reference for a moment there

nimble cairn
#

Oh, that's a neat little hack

nimble cairn
#

I need it to be like that :p

quartz folio
#

If they're aware omnisharp is not running, it's fine

nimble cairn
#

Point 4 is how it is because sometimes the class is within a parent that has a rigidbody, and referencing the transform like that ensures there is no missing reference 🙂

rigid island
nimble cairn
#

I don't have the dev kit installed

#

I don't need it

rigid island
#

then you don't have intellisense + unity 🤷‍♂️

nimble cairn
#

I sure do 🙂

#

@quartz folio @rigid island @somber nacelle Thank you for your assistance and queries!

rigid island
#

you do ? bcuz devkit is part of the Unity extension

nimble cairn
#

You don't need it!

quartz folio
#

Unless you're on an old Unity version or something, pretty sure you do

nimble cairn
#

.NET Install Tool and the C# extension are all you need

rigid island
naive heron
#

how do i instantiate an object under a parent so it follows them when its spawned

quartz folio
somber nacelle
#

pass the desired parent as the last parameter for Instantiate

nimble cairn
#

@naive heron

GameObject parent = new GameObject("Bridge");
child.transform.SetParent(parent.transform);
#

@quartz folio I don't know what to tell you, it works perfectly fine and I have minimal bloat packages.

quartz folio
#

If you have the Unity extension installed—which you should, then it'll have added it as a dependency

nimble cairn
#

No unity related extensions

#

On VSC

rigid island
#

curious to see how it is "working perfectly"

nimble cairn
#

I'm starting her up now, I'll prove this

quartz folio
#

the ol' no access to a debugger, and no refactorings or analysers

nimble cairn
#

I can debug just fine 🙂

quartz folio
#

That's not a debugger, that's just autocomplete

rigid island
#

also missing some other stuff

nimble cairn
#

I know, you were initially asking about the intellisense

fervent furnace
#

if CompareTag("XXXXX") is faster than "XXXXX", then you run =="XXXXX" for n times means it is n times slower than running CompareTag("XXXXX") for n times............

quartz folio
#

CompareTag is faster only because the managed string needs to be allocated with tag, which they only do once

fervent furnace
#

just depend on how comparetag implemented, i think they use unordered_map internally

#

not char by char matching

#

oh wait it still needed to get the hash code for two string then do one comparsion

naive heron
somber nacelle
#

wdym how do you get it? do you not know what object you want the parent to be?

nimble cairn
rigid island
nimble cairn
#
public GameObject cykaBlyatParent;
naive heron
naive heron
nimble cairn
#

There's nothing to figure out

#

Send your code

somber nacelle
#

just pass the object's transform for that parameter

nimble cairn
#

@somber nacelle I think that might be a bit complicated for their skill cap

somber nacelle
somber nacelle
somber nacelle
#

okay so show what you tried

naive heron
#

private void Update()
{
playerpos = playerModel.transform.position;
}
Instantiate(reloadPlayer, playerpos);

naive heron
somber nacelle
nimble cairn
#

No offense! Just want to help of course 🙂

nimble cairn
rigid island
#

this is wrong

naive heron
#

this is what i did to fix it|
Instantiate(reloadPlayer, playerModel.transform.position, Quaternion.identity);

somber nacelle
#

well that just sets its position, it does not set its parent

naive heron
#

its working anyway so idc

#

ty

somber nacelle
#

you need to pass the playerMode.transform as the last parameter as i've said before

somber nacelle
fervent furnace
#

you probably want this

public static Object Instantiate(Object original, Transform parent);
```or this
```cs
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
naive heron
naive heron
#

sorry but thx

rigid island
#

if you move you lose position unless parented

naive heron
somber nacelle
nimble cairn
leaden ice
rigid island
#

also ur parenting it twice

leaden ice
rigid island
#

and this^

nimble cairn
#

Fair enough

fervent furnace
#

there is no overloaded version of instantiate takes only the object and one vector3...

dark kindle
#

does anyone have a workaround for windows' X509 api? I have code to get a list of all certificates in a store: ```

    X509Store s = new X509Store(StoreLocation.LocalMachine);
    s.Open(OpenFlags.ReadOnly);
    foreach (X509Certificate2 c in s.Certificates)
    {
        UnityEngine.Debug.Log("cert: "+c);
    }
#

but it doesnt work

#

essentially it supposed to go to the local machine certificate directory on Windows and prints all the certificates

leaden ice
dark kindle
#

I dont see anything printed

#

that

#

s the issue

#

thats the issue

#

I checked certmgr and im sure I have certificates on my system

#

The code isnt picking them up.

frail nest
#

Hi, I wonder if should I destroy any created sprite? Or the GC will take care of it automatically?
Like

Sprite sprite = Sprite.Create(texture2D, new Rect(0,0,200,200), Vector2.zero):
leaden ice
leaden ice
frail estuary
#

How to freeze Spring Joint movement from side to side only to leave up and down ?

frozen fjord
#

I need help I'm having wayyy too much trouble placing blocks in a minecraft clone

#

My placeblocks method looks like

#
    private void PlaceBlocks()
    {
        if (Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out var hitInfo, reach, blocksMask))
        {
            Vector3 vector = new Vector3((int)hitInfo.point.x, (int)hitInfo.point.y, (int)hitInfo.point.z);
            vector -= playerTransform.forward * 0.001f;

            worldManager.GetChunkByBlock(vector).SetBlockAt(vector, BlockData.GlassBlock, transparent: true);
        }
    }
#

i put line 6 to sorta move outside the block

#
    private Vector2 RoundToChunkPos(Vector2 pos)
    {
        return new Vector2(Mathf.FloorToInt(pos.x / 16f) * 16, Mathf.FloorToInt(pos.y / 16f) * 16);
    }

    public Chunk GetChunkByBlock(Vector3 blockPosition)
    {
        return chunks[RoundToChunkPos(new Vector2(blockPosition.x, blockPosition.z))];
    }
leaden ice
frozen fjord
leaden ice
#

You're doing really fuzzy stuff with the player look direction etc. that's going to be janky

knotty sun
#

use Vector3Int to make sure no fp errors creep in

frozen fjord
#
public void SetBlockAt(Vector3 pos, int blockType, bool transparent)
    {
        int blockIndexX = (int) (Mathf.FloorToInt(pos.x) - transform.position.x);
        int blockIndexY = (int) Mathf.FloorToInt(pos.y);
        int blockIndexZ = (int) (Mathf.FloorToInt(pos.z) - transform.position.z);
        Block block = blocks[blockIndexX, blockIndexY, blockIndexZ];
        block.type = blockType;
        block.transparent = transparent;
        BuildChunkMesh();
    }
leaden ice
#

If you're not working in the realm of discrete grid coordinates you need to throw all your code away and start doing so

leaden ice
frozen fjord
frozen fjord
#

idek what's happening

#

the y coordinate is right

#

everything else is wrong

#

my game

#

is trying

leaden ice
frozen fjord
#

to die

frozen fjord
#

what am i doing 😭

leaden ice
#

The stuff you're doing isn't even taking the Raycast hit normal into account, no idea how it can work without that

leaden ice
frozen fjord
#

is this proper for now

#

i mean

leaden ice
#

You need to lay a solid ground work of helper functions before you start adding features

frozen fjord
#

do you know how i should do this-

quartz folio
#

extension methods out the wazoo

frozen fjord
#

i'm guessing it's in the calculation

#

i mean

leaden ice
#

Well the Raycast hit will be at the edge of the block

quartz folio
#

Draw some things in the scene using Debug.DrawRay/DrawLine

frozen fjord
leaden ice
#

Usually you'd offset that by half a unit inward before converting to get the coordinate

frozen fjord
#

so like negative the surface normal

leaden ice
#

Yes

#

Or half a unit outside

#

To get where the new block should be

frozen fjord
#

Vector3 vector = new Vector3((int)hitInfo.point.x, (int)hitInfo.point.y, (int)hitInfo.point.z);

#

should i

#

do that to this

leaden ice
#

Add half the surface normal

#

Then convert to frid coordinate

frozen fjord
#

so i thought float yay

leaden ice
#

I'm saying offset before you convert to int

#

When you convert to int, then use Vector3Int

frozen fjord
#

oh

#

this is the vector I would be affecting

leaden ice
#

E.g. Vector3Int newGridCoord = hitInfo.point + (hitInfo.normal / 2);

frozen fjord
leaden ice
#

I think there's an explicit conversion

rigid island
#

Vector3Int.RoundToInt

leaden ice
#

E.g. ```cs
Vector3 offsetPos = hitInfo.point + (hitInfo.normal / 2);
Vector3Int newGridPos = (Vector3Int)offsetPos;

frozen fjord
#

is that good

#

now I don't even know what's going on, it works sometimes but then it doesn't?

#

usually it works but then sometimes it'll decide to place blocks in the air

#

oh what is happening

frozen fjord
#

like in minecraft

quartz folio
#

You can draw anything using a number of lines

frozen fjord
quartz folio
frozen fjord
#

I wonder what I could print to check if it's working

quartz folio
#

You could use the debugger and just go over everything

#

there's rarely a reason to print when you can just look at variables and execution directly

frozen fjord
#

wait

#

...it works now?

#

@quartz folio @leaden ice is this code good or stupid (it works)

      private void PlaceBlocks()
    {
        if (Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out var hitInfo, reach, blocksMask))
        {
            Vector3 vector = hitInfo.point + (hitInfo.normal / 2);
            Vector3Int blockPos = new Vector3Int(Mathf.FloorToInt(vector.x), Mathf.FloorToInt(vector.y), Mathf.FloorToInt(vector.z));
            Debug.Log("Point: " + hitInfo.point);
            Debug.Log("Half Normal: " + hitInfo.normal/2);
            Debug.Log("Sum: " + (hitInfo.point + hitInfo.normal/2));
            Debug.Log("Block Position: " + blockPos);
            Debug.Log("---------------------------");
    
            worldManager.GetChunkByBlock(blockPos).SetBlockAt(blockPos, BlockData.GlassBlock, transparent: true);
        }
    }
sour atlas
#

Not sure where the best place to ask this is - it's a Unity Native splines question. I would like to efficiently look up a point on the spline at a set distance away. GetPointAtLinearDistance returns the linear distance so is not what I need. I can walk the spline manually until I reach the distance I want, but this is super inefficient for lots of points... Am I missing a method somewhere? I need a parameterized version of the spline basically.

knotty sun
#

is the spline deforming after creation?

sour atlas
#

It can be yeah

knotty sun
#

so cacheing cumulative distances wont work?

sour atlas
#

Yeah that's my fallback - I can cache once and then use that cache for all the points. I'm just wondering whether that's being done internally somewhere

quartz folio
sour atlas
sour atlas
quartz folio
#

It should, you pass the units from and to

#

just use the right overload

sour atlas
#

Ahh yes sorry missed the second method in the docs

quartz folio
#

I haven't used it that much, I just have a memory of using some jank conversion function in the past 😄

#

I looked at SpriteAnimate and noticed that's what it uses

south cobalt
#

Guys, first line of code is obsolete now, and i am not sure how to edit 2nd one properly so it works, can u help?

sour atlas
rain lava
#

Guys how can I be master at using events and delegates? They are core of game dev, i believe.

cosmic rain
long plover
#

I want a way to make all type of NPCs to look at the player when approached and salute them (salute code is in second pic). How do I do this?

#

Is there a way to make the NPBCrain abstract class already have the function in the second pic in it?

fervent furnace
#

abstract class can have non abstract methods

twilit scaffold
#

So i should learn DOTS and ECS, or have the changed the paradigm?

long plover
fervent furnace
#

pass the parameters this method needs

#

and your method can return something

long plover
#

@fervent furnaceCan I add a start function to the abstract class?

#

I need to add the animator and transform

fervent furnace
#

your abstract class is ScriptableObject......
you can add what even you like

long plover
fervent furnace
#

wait, your npc brain is scriptable object then you cant access the methods from monobehaviour

#

or inherit from it

long plover
#

oh

#

So what do I do? 🥲

#

I remember Fen sent me this code, does this help in any way?

fervent furnace
#

make your monobehaviour base class of other specific npc script eg

public class Letter:Monobahaviour
public class A:Letter
#

yes, put the common methods in the "top" most class

long plover
#

I will try that, 1 sec

twilit tree
#

Hello, i have this error when I build my project, I'm in URP on Unity 2022.3.5f1. The game work normally in editor, sometimes when I build there is no error but the app show just a black screen. This is the error :

Recursive serialization is not allowed for threaded serialization - files cannot be written during serialization callbacks
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()

Unable to write objects to temporary file: Temp/assetCreatePath
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()

UnityException: Creating asset at path Assets/HDRPDefaultResources/HDRenderPipelineGlobalSettings.asset failed.
UnityEngine.Rendering.HighDefinition.HDRenderPipelineGlobalSettings.Create (System.String path, UnityEngine.Rendering.HighDefinition.HDRenderPipelineGlobalSettings dataSource) (at ./Library/PackageCache/com.unity.render-pipelines.high-definition@14.0.8/Runtime/RenderPipeline/HDRenderPipelineGlobalSettings.cs:140)
UnityEngine.Rendering.HighDefinition.HDRenderPipelineGlobalSettings.Ensure (System.Boolean canCreateNewAsset) (at ./Library/PackageCache/com.unity.render-pipelines.high-definition@14.0.8/Runtime/RenderPipeline/HDRenderPipelineGlobalSettings.cs:102)
...

Error building Player: 372 errors
long plover
fervent furnace
#

npc inherits from npcbrain and npcbrain inherits from monobehaviour
i dk what you mean by ScriptableObject tag, ScriptableObject is a class

#

think in this way: inheritance usually means "is" (or are)
you are citizen and citizens are human

#

so
citizen:human
you:citizen

autumn magnet
#
GameObject gun = Instantiate(g);
DontDestroyOnLoad(gun);
gun.GetComponent<NetworkObject>().Spawn(false);
ConstraintSource src = new ConstraintSource();
src.sourceTransform = weaponHolder;
gun.GetComponent<ParentConstraint>().AddSource(src);

I am trying to spawn the gun prefab with this code that works fine but the issue comes with the ParentConstraint cause for some it does not follow the transform of WeaponHolder but whenever I change the index of it to 1 in runtime it does work -_-

fervent furnace
#

i realize that npc is not npcbrain, you can use composition instead (let npc stores one npcbrain)

twilit tree
twilit tree
autumn magnet
twilit tree
autumn magnet
autumn magnet
long plover
#

@fervent furnace I was watching this guide and was trying to follow it. https://youtu.be/0VV24g1SxGU?si=H0qMGDNselBu7E6b

BMo

Learn how to setup Enemy Brains or AI Behavior using Scriptable Objects allowing you to easily drag and drop new ai behavior through the Unity inspector.

Scriptable Objects are a powerful tool in structuring your code cleanly, and here is no exception. With this approach you can setup a complex enemy a.i. behavior tree while all of the behavior...

▶ Play video
fervent furnace
#

yes your npcbrain (or other class that stores data) is scriptable object
while the enemy in world store the reference to its scriptable object

long plover
fervent furnace
#

no, it inherit from npc and npc is monobehaviour

long plover
#

Now I am confused 🥲

#

So I dont have any SO?

#

I am trying to achieve something like this. Where I can make an SO of the desired NPC type (wanderer, teleporter, weaponsmith) and then the person adding these to the scene just need to give them a name, and maybe some other perimiter like teleport location, etc

#

@fervent furnaceI hope it makes sense what I want to achieve

#

I just dont know how to achieve it

sonic notch
#

I currently have a Crowd Simulator using RVO2 for Collision Avoidance and A* for Pathfinding. I'm in school and for my course I need to evaluate something so I need another simple collision avoidance algo to compare with the one I have. I want something as simple as possible because I just want to be done with this course and im stressed. What is something I can use for collision avoidance and use A* for pathfinding as well on it (not a must but probably easiest)?

#

Originally I was thinking Boids but Boids and pathfinding is basically mutually exclusive

#

Don't really have the time to deep dive and learn to how to implement something difficult and complex..

foggy plaza
#

I was using ScriptableObjects to hold and update stats of certain characters. Everything works okay.
But when I load those stats from a json file it works in the Editor, but not in the Build. Am I doing this wrong?

#

Even though debug messages show the correct values, in other areas of the game, the values are not correct in the Build.

fervent furnace
#

use composition

cosmic rain
fervent furnace
#

you can have enemy (monobehaviour) and data (scriptable object), enemy can store the data

cosmic rain
fervent furnace
#
public abstract class Enemy:MonoXX{
  public data theData;
}
public class Enemy0:Enemy;
public class Enemy1:Enemy;

public abstract class data:ScriptableObject;
public class data0:data;
public class data1:data;
```then enemy0 and enemy1 can reference data0 or data1 (or not having data as abstract class if no more variations)
sonic notch
#

And if two groups meet i want them to avoid eachother but not merge

#

pass through basically

#

Im gonna try and just use the RVO I have but without A* and then just use rudimentary collision avoidance with like a raycast and then just rotate to the side if it hits an obstacle or something

fervent furnace
#

multi agent path-planning

#

then you dont need collision avoidance anymore

long plover
fervent furnace
#

The problem of Multi-Agent Pathfinding (MAPF) is an instance of multi-agent planning and consists in the computation of collision-free paths for a group of agents from their location to an assigned target. It is an optimization problem, since the aim is to find those paths that optimize a given objective function, usually defined as the number o...

#

do you know what is inheritance first? i think you dont understand it at all....

long plover
#

For example I want to have this abstract NPCBrain class, where NPCWandererBrain and NPCTeleporterBrain inherites the Think and Salute methods from it. Inside the Think method each of those will use it differently

fervent furnace
#

think scriptable object not scriptable object, it is just some base class
then you can reference it without care what it exactly is

public class NPCBrain:magicalclass{
  public abstract returntype think(parameters);
}
public class ActualNPC:monobehaviour{
  public data theData;
}
sonic notch
#

If you are using raycasts for collision detection, do you create a new one every update? I assume so, just wanna check so Im not "Ray ray = new Ray(transform.position, transform.forward);" every single update unnecessarily.

fervent furnace
#
public class NPCWandererBrain:NPCBrain;
public class NPCTeleporterBrain:NPCBrain;
```assume they both implement think(), then in ActualNPC:
```cs
var result=theData.think(parameters);
long plover
#

@fervent furnace I kinda understand what you are getting at, for me the class names are a bit confusing. Is it possible for you to use my class names in instead of those? I think it will greatly help me understand

leaden ice
#

note that Ray is a struct. Structs are stack allocated and will not create garbage for the GC

fervent furnace
#

scriptable object has nothing to do with how you organize the inheritance tree of different object btw

fervent furnace
#

scriptable object

#

it just add an additional root to your tree for unity to use your objects

sour atlas
#

Another Splines question ( @quartz folio ?) - I can get callbacks from EditorSplineUtility.afterSplineWasModified when the spline container is on the same gameobject as the script with the custom editor... However what I want is callbacks from a spline that is referenced by the script, and I can't see a way to pass the target spline to EditorSplineUtility.afterSplineWasModified?

fervent furnace
#

yes, something likes that

#

btw i think it is better to let the NPC having variation not the data, but idk what your game design is

long plover
storm thorn
#

Hello! I would like to have an add users option on my menu(Something like a friendlist)

I have no idea, how can I call a button to spawn with the selected user profile, so that when they click the name of the added user, they will see the details of the profile.

I'm using firebase as a backend

drifting crest
#

can we change the alpha of an Imgae through code at runtime?

drifting crest
leaden ice
normal quest
#
Color temp = yourImageComponent.color;
temp.a = desiredAlphaValue;
yourImageComponent.color = temp;
drifting crest
leaden ice
#

why did you write .Color when it's called color?

drifting crest
leaden ice
#

In what way was it "not working"?

#

You need to actually read your error messages, don't ignore them.

#

They tell you what's wrong with your code.

drifting crest
#

aight thanks for the help mates

leaden ice
sonic notch
#

Im trying to evalute two different crowd simulators for school. One I'm using is much more complex and the other is simple. The complex one seems to move slower and slow down as it gets further along (seems to still be smooth but the agents move slower) I'm assuming this is due to it being more complicated so lower fps. I'm thinking of just counting FPS instead and using that as the metric for how long it takes agents to get from A to B with the two different algorithms. Since one will in real time be much slower but will actually probably be better in terms of how efficiently the agents move, does this seem reasonable?

#

For the informed im using A Star with RVO2 in one, and just A Star in the other. Obviously the one using RVO2 is the slower one in realtime.

#

But yeah, assuming FPS is good metric that connects them

leaden ice
#

FPS would be a measure of how quickly your computer can run the algorithm

#

It doesn't say anything about how good the pathfinding is

#

which I imagine is what you're actually trying to measure?

#

It's unclear what you're comparing

#

computational performance, or the quality of the paths generated

#

A* is a general purpose pathfinding algorithm which will always find the shortest possible path (guaranteed unless your heuristic function doesn't conform to the requirements)

#

RVO2 is more of a navigation algorithm with collision avoidance iirc

hard viper
#

Stopwatch class is a good tool to measure how long a given evaluation takes, and is a better measure for just one specific thing.
But praetor is right that it’s not clear what you are looking for.

#

Stopwatch just requires you to be able to clearly define a line of code when you start and another line when done.

unique delta
#

When i start the game prefabs are invisible on the ingame camera but i can see them in scene. Can somone help me ?

leaden ice
#

perhaps they're behind it for example

normal quest
#

assuming you are on 2D, check their z position

unique delta
sonic notch
# leaden ice It's unclear what you're comparing

Yeah I'm having a hard time finding a way to measure in time how good a crowd sim is since the computer plays a part. I have two, and I want to measure in time efficiency how long it takes for one to get to its goal, so lets say two groups of 5 passing eachother to get the other side.

A crowd sim using only A star will deadlock a lot and take longer since it won't avoid other agents/characters. But the one using RVO on top of A star will be faster. But my computer however will take longer to simulate the RVO one, since its more complex. So in Real time it will appear slower, even though it isn't. Basically the agents move much slower in the RVO one because its slower to calculate each timestep.

leaden ice
#

So again you need to decide if you're comparing computational efficiency or navigation quality or something else

sonic notch
#

Navigation quality

leaden ice
#

What you can do is just use an in game timer e.g. in FixedUpdate

#
float timer;

void FixedUpdate() {
  timer += Time.deltaTIme;
}```
hard viper
#

you need a metric for navigation quality then, friendo

leaden ice
#

use this in game time to measure how fast the things navigate

#

if you don't care about actual real time running speed this is ideal

sonic notch
#

Yeah but the further along the sim it goes, the slower the agents move because more calculations need to be made. Thats just because of my computer

#

not the algorithms theoretical movement

leaden ice
#

that's why we are using an ingame timer

#

not a real world timer

hard viper
#

i would use Stopwatch for that tbh

sonic notch
#

Oh it will? But not if its in Update right?

leaden ice
#

stopwatch uses system time

leaden ice
#

but generally simulation style things should be using FixedUpdate or an equivalent anyway

#

otherwise they may be inconsistent

hard viper
#

Time.time will use ingame time, and inlcude time spent on other tasks, like overhead and rendering, and managing scripts etc.

#

i think you would need
System.Diagnostics.Stopwatch sw = new();
sw.Start();
CallMyExpensiveMethod();
Debug.Log(sw.Elapsed….formatting);

#

to isolate just the CPU cost of the one expensive method that doesn’t take a whole frame’s computational time.

sonic notch
#

Hm I'm a little confused between the two approaches. Im not trying to evaluate how fast a certain method is, I'm trying to evaluate in a consistent way, how long it takes for my simulation to finish its goal, from A to B, even though how fast the agents move varies depending on where it is in the simulation. Since in the beginning its pretty fast, and the further it gets they move slower, and then start moving faster at the end when some agents finish up. But the time should be consistent through all of these, i dont want it to count as if its taking longer just because the agents are slowing down.

tawdry jasper
#

I'm using this code to read the ground color to determine footstep sound

            Texture2D texture = renderer.material.mainTexture as Texture2D;
            Vector2 pixelUV = _pushing.groundHit.textureCoord;
            Color pixelColor = texture.GetPixelBilinear(pixelUV.x, pixelUV.y);

this works fine in editor, but I just tried building an executable (on osx) and I see in the logs that the color I'm getting back is just "(0, 0, 0, 1)" is there anything special I need to do with materials / textures to do this in the executable? I had to mark the texture as readable in import settings to make this work in the editor, but unity gave me an error suggesting that, in the executable it just gives the wrong value

sonic notch
#

Since they are only slowing down due to the complexity of the code getting more and more demanding in the middle of the simulation.

hard viper
#

both are just ways of measuring time

#

Stopwatch measures system time between two points of code.
Time.time will get you ingame time for a frame

#

so if one frame takes 12 ms and another takes 130 ms, Time.time will tell you that

#

if you want to isolate just the amount of system time it takes to execute a block of code, you start a stopwatch, run the code, and then see what is on the stopwatch

#

does this make sense?

#

Time.time is slightly decoupled from realworld time. System time is basically looking at how many clock cycles your processor took between lines A and B

round violet
#

what should be added ?
com.unity.cinemachine only shows certain methods, but will still recognize the missing ones like CinemachineVirtualCamera

leaden ice
#

But I thought we were interested in the actual simulation-time navigation speed/duration of the characters, not the execution time of the algoriuthm

hard viper
#

i thought he wanted to know about how fast his algorithm executes to compare two algorithms

long plover
#

Trying to give my Teleport Location as a Transform parameter in my SO. It doesnt work?

fervent furnace
#

you cant reference anything on screen in asset

hard viper
long plover
#

Wait, so how do I achieve this? 🥲

fervent furnace
#

so pass it as parameter, as what i told you

round violet
hard viper
#

SO cannot hold a transform well because the SO can exist when the transform does not yet

leaden ice
hard viper
#

you need a different way to reference that position

long plover
#

Not sure how to 🥲

hard viper
#

there are many ways

long plover
hard viper
#

bottom line is: SO should only reference something that always exists

#

eg int teleporter ID. Then have a monobehaviour that searches for the gameobject/transform that matches that ID

#

that isn’t the only way, but there are many ways

long plover
hard viper
#

i gave my SO a field for something that only exists at runtime. I made it work through lots of patching, but it was a really incredibly stupid idea

long plover
hard viper
#

make a singleton that manages all teleporters, and puts them into an array by ID. And let every teleporter have an ID. Write the ID into your SO.

#

singleton can connect teleporter to SO now

icy herald
#

Can someone help me with a button? I used this code before adding the ability for the box to press the button. But now, every time my player moves away, the button deactivates, even if the box is still there.

long plover
tawdry jasper
long plover
soft chasm
#

General Question: What would be the best way to handle Pokemon style gameplay? Not the turn based stuff, I'm more meaning the way they handle movement and gameplay. As in, they move around in a 2D top-down world and then enter battles which takes them to an entirely different screen dedicated to the battles.

If I was to recreate that idea of gameplay (switch between movement and battle), what would be the best way to do this? To have the 'battle' screen be GameObject overlaying the main scene and just SetActive(true/false) a parent to enable/disable the battle screen - or have the battle happen in a different scene altogether. Would there be any advantages/drawbacks to either?

#

I understand I'm asking a rather vague question of a rather in depth mechanic, a generally vague answer will also do just fine 👍

long plover
#

If so, what class do I put it in?

leaden ice
#
// Define the enum
public enum TeleportLocation {
  Homebase,
  FiringRange,
  Arena
}

// make a field of that type
public TeleportLocation location;```
long plover
leaden ice
#

why not something like:

Vector3 GetPosition(TeleportLocation location) {
  switch (location) {
    case TeleportLocation.Homebase:
      return new Vector3(0, 5, 10);
    case TeleportLocation.Arena:
      return new Vector3(5, 1, 6);
    // etc...
  }
}```
long plover
long plover
vagrant blade
#

transform is a property of a game object, your location is an Enum type

#

And your GetPosition function doesn't return in all cases, you need to include a default: to your switch statement.

leaden ice
#

why are you tryin gto do location.transform.positon (which makes no sense??) instead of calling the function we just wrote?

long plover
#

Like this?

long plover
fervent furnace
#

do you know what is enum

dark kindle
#

I tested in another engine, and without printing length I was able to get output

leaden ice
#

looks like you'd have to use a native plugin if you want this information

dark kindle
#

it's a big component of my project so it kinda sucks

round violet
#

So i used this Unity docs example so I could "make" a dict in my inspector, all worked fine until i tried to edit the list after i compile after correcting an error.
now i cannot add items, but i cant still remove

here is my code and inspector:

mellow sigil
#

What happens when you try?

round violet
#

nothing

#

just me pressing the "+" icon

leaden ice
#

it will only iterate up to the min of the two

#

I wouldn't use two separate lists here

#

I would use one list containing a struct with both the key and value data in it

hard viper
#

I would like to request feedback still, on the topic of: does this sound like a good system to use for collectibles?

round violet
mellow sigil
#

The docs example isn't complete. It just shows the gist of it.

long plover
# fervent furnace do you know what is enum

I do know what it is and have used it before, doesn't mean I can focus well with a strong migraine, I just need to finish this code ASAP so I am ready for my exam tomorrow

long plover
fervent furnace
#

the default access modifier is private

leaden ice
long plover
#

ohhhh, damn my brain really is turned of 😭

fervent furnace
#

is your exam related to this game you are making on?

long plover
hard viper
#

you should use this singleton implementation

#

very simple way to implement singletons in unity

heady iris
#

I have multiple kinds of singletons (how ironic)

#
using UnityEngine;

public abstract class SingletonPrefab<T> : MonoBehaviour where T : SingletonPrefab<T>
{
    private static T _instance;
    public static T Instance 
    {
        get
        {
            if (_instance == null)
            {
                _instance = Instantiate(Resources.Load<T>("SingletonPrefab/" + typeof(T).Name));
            }

            return _instance;
        }
    }
}

my fave

#

this is used to set up some DontDestroyOnLoad objects

hard viper
#

the singleton class I linked derived from monobehaviour

#

it's got everything you need for singletons in unity

#

its GetInstance() is thread-safe, can check scene for already-existing monobehaviours in the scene, and allows DontDestroyOnLoad optionally

#

it's just a lot better

heady iris
#

this singleton yoinks itself from the Resources folder

hard viper
#

check it out. it's a very good implementation.

heady iris
#

returning null when the game is quitting is a decent idea

#

i ran into a similar problem when unloading a scene

#

the singleton object could get destroyed before something else tried to use it (to unsubscribe from events)

hard viper
#

i think I added in an oprional protected field to avoid DontDestroyOnLoad

heady iris
#
using UnityEngine;

public abstract class SingletonSO<T> : ScriptableObject where T : SingletonSO<T>
{
    private static T _instance;
    public static T Instance 
    {
        get
        {
            if (_instance == null)
            {
                _instance = Resources.Load<T>("SingletonSO" + "/" + typeof(T).Name);
            }

            return _instance;
        }
    }
}
#

extremely similar idea to the first one

hard viper
#

hold up something is wrong with the implementation I linked. The implementation I know has a lock for threads

heady iris
#

is accessing a unity object from anything but the main thrad ever legal

#

i haven't really wanted to do that before

#

I know that the video said that implementation wouldn't handle multithreading correctly.

hard viper
#

yeah. I'm pretty sure you need a lock

autumn moth
#

do you guys actuall watch then do in unity learn or do while watching ;-;

#

i feel its easier for me to do the latter ahsdbahwdb

rustic arch
#

Hello everyone! Did anyone experience any issue with the camera movement after switching to new player input system? When I'm just moving with A/D around an object or corner or anything looks smooth but if a move the camera and press A/D it's becomes really jittery. I'll attach a video below if anyone had this problem. I've been spinning around it all day long 😭

long plover
heady iris
#

That can cause gnarly jittering (because it's wrong)

rustic arch
heady iris
#

Yes, that's wrong

#

Mouse input is an absolute amount. It's not a rate of change, like a joystick would be

#

Don't scale it by deltaTime.

rustic arch
#

I'll try it and get back to you, thank you!

long plover
#

I cant seem to get the player to teleport when they get close/touch the soldier. What am I missing here?

heady iris
#

You'll need to adjust your mouse sensitivity to compensate for this (cut it by a factor of 60 or something)

heady iris
#

since longer frame times mean the mouse moves further

long plover
fervent furnace
#

where is the update

long plover
#

It worked for the wanderingbrain

unborn flame
#

why is it taking so long? What should i do?

heady iris
#

If unity gets stuck for that long, just kill the process and reopen it

unborn flame
long plover
#

Seems like the player teleport line is not working correctly

heady iris
#

the library is full of cached files, basically

fervent furnace
#

log the return of GetPosition not the enum value

rustic arch
#

But it still does the same

long plover
heady iris
rustic arch
long plover
#

So its correct location

heady iris
#

If you’re using a rigidbody, turn on interpolation

rigid island
heady iris
#

If you’re using a character controller, just move in Update

long plover
fervent furnace
#

magic hard code number, btw where is the player after teleported, probably the magic number is wrong

long plover
#

it SHOULD teleport the player exactly there in the back of the tent

fervent furnace
#

is there any other thing control the player position

long plover
# fervent furnace is there any other thing control the player position

There is this script

public class PlayerMove : MonoBehaviour
{
    public CharacterController controller;
    public float speed = 12f;
    public float gravity = -9.81f * 2;
    public float jumpHeight = 3f;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    Vector3 velocity;

    bool isGrounded;
    bool isMoving;

    private Vector3 LastPosition = new Vector3(0f, 0f, 0f);
    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        //Ground check
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
        //Reset velocity if grounded
        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        // Getting the input
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        // Creating the moving vector
        Vector3 move = transform.right * x + transform.forward * z; //(right - red axis, forward - blue axis)

        // Actually moving the player
        controller.Move(move * speed * Time.deltaTime);

        // check if the player can jump
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            // Going up
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        //Falling down
        velocity.y += gravity * Time.deltaTime;

        //Executing the jump
        controller.Move(velocity * Time.deltaTime);

        //Check if the player is moving
        if (LastPosition != gameObject.transform.position && isGrounded == true)
        {
            isMoving = true;
            // for later use
        }
        else
        {
            isMoving = false;
            // for later use
        }

        LastPosition = gameObject.transform.position;
    }
}
#

My groupmate made that

rustic arch
fervent furnace
#

havent used character controller, but try to use controller.move position? , cc will override transform position iirc

rigid island
heady iris
#

I'm not sure I'd want to use a rigidbody for a first-person camera like that

rustic arch
heady iris
#

two unrelated things

rustic arch
fervent furnace
#

just checked docu, there is no method likes rb.move position in character controller....just follow the link posted by navarone

wanton root
#

i dont know where to ask but how do i fix this error? Internal build system error. read the full binlog without getting a BuildFinishedMessage, while the backend process is still running

long plover
#

Not sure how to call the controller in the PlayerMovement class from the Teleport class

rigid island
long plover
long plover
rigid island
upbeat raven
#

hi everyone. i have problems with connecting my unity to sql. someone please text. its very important

heady iris
#

you're going to need to share code and provide some more information

upbeat raven
#

is there evrything ok?

#

because when i trying to register an user i have :User creation failed. Error

west lotus
#

Considering your !ide is not configured properly no

tawny elkBOT
west lotus
#

But since you are getting the debug.log it means you are getting a response different than 0 from your php script

upbeat raven
rigid island
#

also should not use WWW class

#

its deprecated

#

use UnityWebRequests

upbeat raven
#

i was trying but nothing changed

knotty sun
#

so you should be looking at the server log

simple egret
#

I'll name myself ', '', ''); DROP TABLE players -- and register, brb
Please parameterize your queries

harsh coyote
rustic arch
harsh coyote
#

Ok thanks, I'll try that too.

harsh coyote
#

I tried using Cinemachine, set Update Method to Fixed Update and it seems to be better.

hexed pecan
true blade
#

would anybody be able to tell me why my script isnt detecting any collisions

#

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting.Dependencies.NCalc;
using UnityEngine;

public class ScoreTrigger : MonoBehaviour
{
private ScoreCounterBlue counter;
private float Score = 0;
//public Collider colliderZone;
// Start is called before the first frame update
void Start()
{
counter = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<ScoreCounterBlue>();
}

// Update is called once per frame
void Update()
{
    //counter.countScore(Score);
}

private void OnCollisionEnter(Collision Col)
{
    if (Col.gameObject.layer == 3) {
        Score++;
        Debug.Log("BoxEntered");
        counter.countScore(Score);

    }
}

private void OnCollisionExit(Collision Col)
{
    if (Col.gameObject.layer == 3)
    {
        Score--;
        Debug.Log("BoxExited");
        counter.countScore(Score);
    }
}

}

swift falcon
#

2D or 3D game?

true blade
#

3

tawny elkBOT
true blade
#

'3d

swift falcon
#

Does the other collider well have a collider?

#

I believe one of the Gameobjects should also have Rigidbody

true blade
#

well im trying to have a certain spot on the ground be the trigger so that has a collider ith the box set as a trigger

#

no rigidbody

#

but the gameobject im trying to detect has a rigidbody and a collider

somber nacelle
#

click the link i sent

true blade
#

im not sure what type of collision i have

#

its a box collider in one object with a box collider set to trigger on another

#

ive tried detecting with layers with tags and with my objects name that im trying to detect

#

nothing works so far

somber nacelle
#

have you gone through the link i shared that takes you through all of the troubleshooting steps you need to check? i'll give you a hint, it will show you what you've done wrong

true blade
#

i did and i got to the collision matrix chart but im a bit confused as to what im looking at

somber nacelle
#

scroll down to see what each thing means

true blade
#

im still a bit confused

#

i tried checking the kinematic box on my gameobjects im trying to detect but that just freezes them in place unless im actively moving them

somber nacelle
#

your issue isn't whether they are kinematic. you are using a trigger collider and expecting to get a collision message.

true blade
#

but when i try to use ontigger its telling me i have an incorrect signature

somber nacelle
#

because you do. again, see the link i shared

true blade
#

alright

delicate flax
# true blade

yes, because OnTriggerEnter takes a Collider not a Collision

true blade
#

ah i see

delicate flax
#

ez to miss since they look so simmilar 😄

true blade
#

sorry im pretty new to these things and its all the little stuff that i tend to miss

delicate flax
#

and OnCollisionEnter takes a Collision

true blade
#

yeah

#

its all working the way i want now

#

thank you simex and boxfriend, probably wouldve been banging my head against a wall for a few more hours without your guys help

dusty hedge
#

I am having a bit of trouble compling for linux;

cannot execute binary file: Exec format error unity

I get that when I run the complied file. After some research I have seen it is because my unity project is suported for 64bit only, and my OS is 32bit. Is there a solution for this? I am using unity 2022.3.16f1

heady iris
verbal gate
#

Hi, is anyone free to help me go through some issues im having. I am using the new input system and using the rebindUI sample from it but the keybinds aren't being preserved across scenes

dusty hedge
#

damn i spent ages working on this

verbal gate
#

does anyone know how i can fix this or help debug it?

dusty hedge
#

thanks anywayy

dusky pelican
#

Hello, i have ScriptableObject X. I used to Instantiate X for creating instance of class. Now i added List<ScriptableObject> Y to X. After that in editor, i add ScriptableObjects to Y.

So if i instantiate X, do i get instances of Y objects too? or Is there any way to get instances of Y?

heady iris
#

No. The original object and the new object's lists will refer to the same objects.

#

You know, I'm not as confident as I thought I was 30 seconds ago. Let me go look.

dusky pelican
heady iris
#

What are you trying to accomplish here?

dusky pelican
#

I have Gun SO and GunSkin SO, so list will be List<GunSkin>.

#

I need to add GunSkins to Gun

#

Also i am trying to get instances because i use SO as pre defined datas

#

So i can save and load easily

#

Long story short, i just need to get instances of every object in list.

heady iris
#

okay, yes, it's as I expected

#

instantiating an object just copies over the references it has

#

that makes sense; otherwise instantiating an object would give it copies of things like materials

heady iris
dusky pelican
heady iris
#

"mutating" means to change data

#

so yes, you're modifying the objects

dusky pelican
#

Yes.

heady iris
#

I would suggest storing the data that changes somewhere else

#

GunSkin is a definition of a gun skin

#

something else should keep track of which gun skins you have

#

that completely avoids the issue

dusky pelican
#

Okay, i will try to do that way. Thank you so much!

fallow sail
#

hello, i have a basic game on google play. For production release i need to complete closed test. For closed test i need 20 volunteers. Can anybody help me to download my game to their device?

simple egret
tacit swan
#

when im playing a timeline using PlayableDirection.Play() it seems like the music starts playing before the entire project gets compiled resulting in the timeline signals being off. Is this a problem that will be resolved if i just compile and build the game?

faint brook
#

Whats the best (working) way to use google apis in unity. I looked at the .net client but it says unity isnt supported. for context I am trying to acsess google sheets api through http requests but oauth is needed and to my knowledge that requires google apis. let me know if this is inncorect

hard viper
#

how do I define a generic with the constraint that < is defined?

simple egret
#

Operators overloads are static, and interfaces forcing static members to be implemented is not supported by Unity

hard viper
#

unfortunate

#

well, is there a catch-all for T being a numeric type?

#

like int, float, uint, long, etc... which would have those defined?

simple egret
#

Not that I know of. Generic math and stuff like INumber<T> was added in .NET 7 or so

hard viper
#

hmmm, maybe I'll try IComparable

simple egret
#

Ah yeah there's that one, should work for most of these types

hard viper
#

yeah. i just wanted to constrain more, so I don’t think in the future to put random Icomparables into this generic

#

future stupid proofing

rocky basalt
#

Is there an easy way to draw a few lines between vertices without applying a bunch of LineRenderer components in the editor?

I have a few quads and I just want to be able to draw an "outline" between the four corners of each quad on demand

twilit scaffold
#

So to get the full performance out of Unity, i should learn/use DOTS and ECS? Or have they changed to some other paradigm already?

rigid island
hard viper
#

it’s a different workflow

spring creek
hard viper
#

DOTS/ECS is more efficient because it is a different representation

rocky basalt
twilit scaffold
#

Ok, thank you both

rigid island
#

line renderer takes an array of points, you can make as many as you need

hard viper
#

it’s like how you can represent everything with Matrices or gameobjects. Obviously matrices will make everything fast af, but that requires you to create matrix representations. Similar thing

twilit scaffold
#

i see. Ok, i will have to see if i can even comprehend the different way of thinking then

hard viper
#

note that computational time you save may come at the cost of more time programming

#

you could code a game in assembly, and it would be fast as shit. but that involves coding in assembly

twilit scaffold
#

an important consideration as a single person 'team' :/ not counting my extended team (you's guys)

hard viper
#

the whole point of unity is to use the engine to save time coding

latent latch
#

ECS is worth it if you're building some large unit game like an RTS

twilit scaffold
#

I am working on a RPG, with a limited number of units on screen at the same time. Complex customizable character though, so i have to figure out how to handle the 650+ morph targets/baking

hard viper
#

then don’t fuck with ecs

#

you won’t need it

twilit scaffold
#

cool deal. so no benefit trying to'ECS' a bunch of trees or the like.. that is a different system entirely? (Just today starting to look at ECS)

hard viper
#

it’s a very different way of programming a game

spring creek
twilit scaffold
#

I am coming from the Unreal way of doing things, so a lot of this optimization was automatic there. completely different here

hard viper
#

ECS excels at processing a huge number of separate things at once

twilit scaffold
hard viper
#

imagine trying to process a simulation for a real gas, for example

#

where you have 10 million particles, all colliding with each other

#

you will not make it with 10 million dynamic rigid bodies

twilit scaffold
#

i see. that makes sense. So i should just depend on the Unity 'standard' way for the usual things like Instancing multiple trees/meshes and not even bother considering it for that then

hard viper
#

that is how I would start

#

or start with godot if you know nothing about unity

#

godot is growing, while unity is shrinking

twilit scaffold
#

Nah, godot cannot even handle my Character due to the massive initial size because of the Shape Keys

#

Ya think? hmm. i was hoping Unity was about to do a big push forward

hard viper
#

last year’s big announcement screwed up unity’s upward trajectory. lots of people jumping ship to godot

worthy tinsel
twilit scaffold
#

sounds good, thanks

hard viper
#

that said, Godot isn’t fully ready, but being a part of the community as it grows will give you a big advantage if you stay with them

#

whereas Unity is very established

#

and most new features are experimental and half-baked

rigid island
twilit scaffold
#

coming from Unreal, i am used to half baked, and flat out broken in some cases😄

rigid island
hard viper
#

it will take time for godot to catch up. but they will steadily grow

#

and being open source will lead to far fewer “sealed class fuck you lmao” moments

twilit scaffold
#

indeed

hard viper
#

and no “i have no idea what this does because this code injects proprietary C++ code” moments

rigid island
latent latch
#

unity terrain tools haven't been updated since 2012

hard viper
#

unity terrain tools are ass

rigid island
#

exactly

latent latch
#

roblox has a better terrain editor

#

and no one uses that

hard viper
#

what has driven me nuts is the whole physics2D being injected

twilit scaffold
#

That does bother me, but after working with Unreal for years, i realized that while it can do 'everything', the amount of time it takes to do basic things is not feasible for an individual. On the other side, Unity seems to have a faster development cycle for individuals. and Godot, while deserving of a big thumbs up, is just not technologically on par, yet

latent latch
#

with that being said, terrain editor is still pretty good at optimization and culling

hard viper
#

want to see what effectors do? gfy
want to know how joints work? gfy
want to modify physics simulation? gfy
want to actually make custom parametrized colliders? gfy, and CustomCollider2D wasn’t even properly tested lol

quartz folio
twilit scaffold
hard viper
#

i’m still holding my breath for full C# v9 support

quartz folio
#

it'll come with the transition

#

and then you'll have C# 13 by that point 😄

hard viper
#

yeah… given godot is building their C# compatibility now, I expect the first version they support to be C#13+

#

anyway, point being, it’s worth checking out godot as it grows if you have no experience with unity

latent latch
#

think of how many lines of code ill be saving with struct initializers

hard viper
#

and records

quartz folio
#

primary constructors, namespaces without scopes

#

regex and json source generation

#

nuget...

#

raw string literals 🤤

#

string interpolation that doesn't allocate at the point it's declared

#

a non-shit GC

rigid island
hard viper
#

unity interfaces into box2D. You can see how box2D works. You can see how unity works within C#. But you can’t see the critical junction in C++ where unity actually works with box2D

rigid island
#

ah yeah 😢

hard viper
#

as in, the actually important part is invisible and non-editable

#

which is part of why i built my own physics engine from scratch

#

i needed to modify some critical things where Unity did not allow me

covert shard
#

hey there, i am having a weird issue that i hope someone here has been through before. for some reason just moving the unity scene is causing my high end computer to reach 95 cpu and high gpu usage and as soon as i stop everything comes back to normal. is there a setting that i need to turn on or off that i should know about?

spring creek
covert shard
#

how do i profile the scene? i though i could only profile the game running

calm talon
#

I have a Light 2D component on a tiled sprite and I'm wondering how I can find the corners of said sprite to align the light's shape to so I don't have to manually resize it

covert shard
#

nvm found it

hard viper
#

i don't think sprites really have corners, unless you read the pixels in it

#

and then actually search for specific patterns etc

calm talon
#

well I do have a collider on it

hard viper
#

then use the collider shape

#

call GetShapes on the collider, and sift through the shapes.

calm talon
#

alright

hard viper
#

also, graphics and hitboxes don't mix well

calm talon
#

I tried using a polygon collider's path but that didn't work out lol

calm talon
hard viper
#

is it a big complex shape?

calm talon
#

nope

#

s q u a r e

hard viper
#

bruh, just calculate it

covert shard
#

welp windows shift s isnt working

#

but is turns out that the main thing that has spiked

spring creek
covert shard
#

i did that that didnt help but that should be a big problem just a restart from my computer, but the main thing that spiked in the unity editor is just application.idle

#

what does that mean?

#

ama restart until i get a response ill be back shortly

#

im back

#

damn, after i restarted the performance only is affecting the gpu now the cpu only increases by like 5%

foggy sentinel
#

does someone know how I would fix this. I dont want the player to be able to float like this on the edge but If I shrink the width of the collider it will be smaller then the body.

rigid island
#

this is a tricky problem to solve

#

a raycast can help you check if you're not grounded then push the player slightly off

foggy sentinel
#

Ok Il try that thank you

cosmic rain
#

Then you'd naturally slide off if the center is out the edge.

foggy plaza
# cosmic rain Hard to say anything without seeing your implementation.

It's too much code, but I changed it and put the management of the values in a component in the gamemanager. It seems that ScriptableObjects are "baked" in the build so the values are not really editable on runtime, it's just confusing the Editor has a completely different behaviour.

cosmic rain
#

That's why if you save them to a file as json to load later it should be working.

#

If it doesn't there's something wrong with your code, which is why I mentioned that we need more details.

foggy plaza
#

I did that, and I debugged the messages, the values were saving and loading correctly in the json. The code worked in the Editor but not in the Build. I am using 2022.1.18f1

#

But I like what I did now, so I think I am just gonna refrain from saving data to ScriptableObjects

indigo hound
#

Hey there, so I've been making a game with powerups, and for each 'powerup state' I've made a scriptable object. In it, I have a 'HandleMovement' method, where the necessary stuff is done to make him move. This method is then called in FixedUpdate in my PlayerController script. Sadly, the velocity value doesnt add up like it should, so my player just stands still and cant move around. When I set the HandleMovement method directly (without using SO's) in the PlayerController script, it does work. Through the Scriptable object though, it doesnt.

Below you can find the (simplified) HandleMovement method, and the place where it's called in my PlayerController script. Could anyone help me with this, or explain why it doesn't work?

HandleMovement():
velocity.x += inputDir * physicsConstants.walkAccel;

PlayerController, FixedUpdate();
playerPowerupStateController.GetActivePlayerPowerupState().HandleMovement(controller, directionalInput, velocity, this, isDucking, isSkidding, isRunning);
controller.Move(velocity * Time.fixedDeltaTime);

hard viper
#

how does your SO encode the information for which function to use

indigo hound
#

Sorry I dont understand I think, what do you mean?

hard viper
#

if I understand, you have one SO for normal mario, and one SO for frog mario which would have different controls in water, or something like that

indigo hound
#

Yeah

hard viper
#

and each SO is a different asset of the same type?

indigo hound
#

No, so let's say we have FrogMario, he would have a different script which derives from a general PowerUpState SO, which can then override the HandleMovement() method so it fits the frog behaviour

hard viper
#

ok, so this sounds like a case to use an interface or abstract class, potentially

#

eg IPlayerMovement

#

then your powerup SO (eg an SO with info about a mushroom, with sprite and state etc) can take a TypeReference to a type that implements IPlayerMovement

#

class typereferences in a plugin that lets you serialize a reference to a specific type, btw

#

then I would define methods:
public interface IPlayerMovement {
public bool AllowJump {get;}
public void HandleJump();
public void HandleMove();
}
etc.

#

it’s what you’re doing now, but with an interface (or abstract class) instead of SOs

indigo hound
#

Hmm I see yeah, I might have to try it. And is there any reason why the HandleMovement() method doesnt work through the SO? While it does work if I place it directly into my PlayerController script?

hard viper
#

you could probably use SOs, but it is a weird use case because you might want to instance to hold variables in future, and SOs are weirdly persistent

#

like if my SO has bool isGrounded, which it uses to figure out what to do in HandleMovement(), you’re going to see some weird stuff happening with respect to starting with old values

#

which you can totally overcome, but is an additional pain point which is avoided with non-SO solutions

#

if I had to guess, you are storing fields in your SO which are used for calculation?

#

or a reference to the rigidbody, or other things which only exist in the scene?

indigo hound
#

Alright thx! My SO has data for the Animator it has to play, base -and crouchsize, ... so i can set it whenever a new powerup is picked up. It doesnt store the rigidbody though or speedvalues, those are stored in a seperate class PhysicsConstants

hard viper
#

I see. Also, I believe what you are doing is called the Strategy Pattern. That might help you find resources on different ways to implement it.

indigo hound
#

Alright that could be helpful thx

hard viper
#

good luck

indigo hound
#

Thanks!

hard viper
#

in your case, it would be something like:


public class FrogMovement : PlayerMovementStrategy {…}

public class Powerup : ScriptableObject {
[field: TypeExtends(typeof(PlayerMovementStrategy)), SerializeField] public TypeReference playerMovementType;
// Animator settings…
}```
#

this defines the powerup’s SO as having whatever settings are completely immutable and locked in. Then TypeReference lets you instantiate whatever powerup movement behaviour you need based on the SO. Since the PlayerMovementStrategy isn’t an SO, you can create, nuke, reset etc it at will, without worrying about old values.

swift falcon
#

Hey guys

#

I have a problem

#

Where my damage prefab is not showing at the objcet being damaged

#

Here is how i instantiate:

swift falcon
#

The prefab is not spawning at the damaged object

#

I don't even use localPosition

#

What's the error here

rigid island
swift falcon
#

Cause it's kinda hard lol to just show it

swift falcon
#

It's a little laggy, I apologise

#

But here you go

rigid island
#

all good

swift falcon
#

I don't know how to fix this

#

OBS bro

rigid island
swift falcon
#

It is

#

Let me tell you the timestamp sorry

#

At around 0:18

#

It's the yellow "1"

rigid island
#

oh ok and which object has the script you posted

swift falcon
#

Butter guy

rigid island
#

and the prefab for text

#

also maybe try transform.localPosition for Instantiate param

#

Im thinking it might be spawning behind the sprite as well , so maybe an offset would help. along with rotation

#

ie make the rotation look at camera

rigid island
#

im thinking rotation / position

swift falcon
#

how do i fix that

#

lol

rigid island
#

hmm first add localPosition and add offset, because position spawns it at center of npc since thats where ur pivot is

#

rotation wise you could do LookRotation from camera

swift falcon
#

wont that mess it up

rigid island
swift falcon
#

or is it different

rigid island
#

yeah sort of

swift falcon
#

alright

rigid island
#

you could also put Debug.Break after Instantiate, and it will pause the simulation so you can see where its spawning exactly

swift falcon
#

yeah navarone

#

it's not working

#

because i dont move the sprite

#

i move the parent

#

which means localPosition can't change

#

it'll stay in the same place

#

let me make it debug.log transform.rotation

rigid island
swift falcon
#

alright

rigid island
#

you will see it inside the hierarchy and press F to focus on it

swift falcon
#

aight

#

thanks for telling me it exists

#

it's helpful

#

AIght

#

@rigid island

rigid island
# swift falcon

this one doesnt help much, show the one in the scene while game is paused

#

like where is it inside the scene view

swift falcon
#

this is the butter parent

#

sure

#

OH

#

Do you reckon its the width of the text box?!

#

Oops

#

💀

#

It is

rigid island
#

lol

swift falcon
#

lol

#

thank u

#

at this point you belong in the game credits 💀

rigid island
swift falcon
#

:)

#

lol 1 more thing @rigid island concerning this game if you could help

#

i might as well as right now

rigid island
#

sure

swift falcon
#

when my player rigidbody hits one of the butter guys, he goes flying

#

same with when i make the terrain a little bit elevated

#

increasing mass doesn't just help

#

because theni n eed to increasethe speed a ton

rigid island
#

are you using physics to move?

naive heron
#

anyone know how i can get the rotation to look more natural and less forced?
code:
rayHit.rigidbody.AddForceAtPosition(direction * 10, rayHit.point, ForceMode.Impulse);
rayHit.rigidbody.AddTorque(Vector3.Cross(Vector3.up, direction) * 10, ForceMode.Impulse);

swift falcon
rigid island
swift falcon
#

really?

rigid island
#

also inputs should be grabbed in Update. rigidbody in FixedUpdate

swift falcon
#

ah

#

sure let me try

#

freeze position?

rigid island
#

yeah

rigid island
#

anything you dont want moved by other colliders

swift falcon
#

oh

rigid island
#

since you're moving it with code constraints will have no effect on your code but help lock in rigidbody

swift falcon
#

oops

#

it's not letting me move

#

💀

rigid island
#

oh right maybe only kinematics it works

#

maybe try to unlock X and Z only

swift falcon
#

but then how do i make him jump in the future

rigid island
rigid island
#

change rb.velocity to character Controller.Move(moveDir * Time.deltaTime * speed)

swift falcon
#

Thanks man!

#

If I have any more problems I'll write them down here

#

But you helped a lot

#

🫡

rigid island
#

good luck!

swift falcon
#

thanks!

#

this game is gonna look goooood

keen imp
#

hi is there someone here who would like to help me on the Generics or do i need to go in the beginner channel ?

spring creek
keen imp
#

no generic like the code term

spring creek
#

Ok, then just ask.

keen imp
#

might be abit long i will write it in a txt and write here in one blow (sorry again 😭 i'm new)

#

So I'm trying to implement a A* pathfinding algorithm.
I have created a grid class where i can put a generics in the constructor to put a custom type for example a PathNode class that i made.
So when i try to create my object in my script here is my A* script,my grid script and my nodes script

public class Astar
{
    private Grid<Node> grid;

    public Astar(int width, int height)
    {
        grid = new Grid<Node>(width, height, 5f, Vector3.zero, (Grid<Node> g, int x, int y) => new Node(g, x, y));
    }

    public class Node
    {
        private float Gcost,Hcost,Fcost;

        private int x, y;
        private Grid<Node> grid;
        public Node LastNode;
        public Node(Grid<Node> grid, int x, int y)
        {
            this.grid = grid;
            this.x = x;
            this.y = y;
        }

 public Grid(int width, int height,float nodeRadius, Vector3 Origin, Func<TGridObject> creategridobject)
        {
            this.width = width;
            this.height = height;
            this.nodeRadius = nodeRadius;
            gridArray = new TGridObject[width, height];
            debugTexture = new TextMesh[width, height];
            //Debug.Log(width+"/"+height);

            for (int x = 0; x < gridArray.GetLength(0); x++)
            {
                for (int y = 0; y < gridArray.GetLength(1); y++)
                {
                    gridArray[x, y] = creategridobject();
                }
            }}


    

i get an error, that say incompatible anonymous function signature (i'm on RiderIDE )

#

i don't really understand what is an anonymous function beside my research

heady iris
#

An anonymous function is a function that has no name.

#

You declare an anonymous function by using the => operator

#

The only anonymous function I see in your code is this

#
(Grid<Node> g, int x, int y) => new Node(g, x, y)
#

This is a three-argument function.

#

Grid's constructor takes a Func<TGridObject> as the last parameter.

#

That's the type for a function that takes 0 arguments and returns a TGridObject

#

These are incompatible.

keen imp
#

oh okay so if i make a function that create 1 node with 3 args it won't work then but it will not be anonymous at least ?

heady iris
#

I think you need to rewrite the Grid constructor.

#

It sounds to me like you want to be able to pass the x/y coordinates to the "create grid object" method

#

as well as the grid itself

#

But Func<TGridObject> doesn't allow for any arguments.

#

What does allow for arguments is Func<Grid<TGridObject>, int, int, TGridObject>

#

This is a three-argument function that returns a TGridObject

#

If you switched the constructor to take that, and then passed those arguments on this line...

#

gridArray[x, y] = creategridobject();

#

...it would work

keen imp
#

okay i need to work back on my grid then thank you 👍 notlikethis back to work

untold quail
#

So my terrain is made of closed spirte shapes. Using that with Unity's 2d lighting system though causes the shadows to cast incorrectly around a rectangle outlining the terrain shape. Is there anyway I can fix the shadows without manually setting each point of the shape of the shadow myself? Or, an alternative to using sprite shapes for my terrain in general that still gives me the freedom to create levels not on a grid

crude mortar
#

I believe that all the necessary API exists to do so

untold quail
#

Sounds like a fun challenge, I'll try my best!

#

thank you! :0

indigo hound
indigo hound
#

I changed it to 'Inherits', but afterwards when I try to call the methods from the PlayerMovementStrategy class, it can't find the method due to this error:
Any idea how to fix this? 🙂

quartz folio
#

Doesn't this thing serialize types, not instances of types?

indigo hound
#

Not sure I'm not too familiar with it yet

eternal tusk
#

how to shorten the stretching distance when using the "Configurable Joint"?

frosty snow
#
void Awake() {
    Collider[] colliders = GetComponentsInChildren<Collider>();
    
    foreach(Collider c in colliders) {
        if (c.gameObject != this.gameObject) {
            ragdoll_colliders.Add(c);
        }
    }

    Rigidbody[] rigid_bodies = GetComponentsInChildren<Rigidbody>();
    
    foreach(Rigidbody r in rigid_bodies) {
        if (r.gameObject != this.gameObject) {
            ragdoll_bodies.Add(r);
        }
    }

    foreach(Collider c in ragdoll_colliders) {
        c.isTrigger = true;
    }

    foreach(Rigidbody r in ragdoll_bodies) {
        r.isKinematic = true;
    }
}

void turn_ragdoll_on() {
    if (cached_animator != null) {
        cached_animator.enabled = false;
    }

    if (cached_third_person_controller != null) {
        cached_third_person_controller.enabled = false;
    }

    if (cached_character_controller != null) {
        cached_character_controller.enabled = false;
    }

    foreach(Collider c in ragdoll_colliders) {
        c.isTrigger = false;
    }

    foreach(Rigidbody r in ragdoll_bodies) {
        r.isKinematic = false;
    }

    in_ragdoll = true;
}

void turn_ragdoll_off() {
    foreach(Rigidbody r in ragdoll_bodies) {
        r.isKinematic = true;
    }

    foreach(Collider c in ragdoll_colliders) {
        c.isTrigger = true;
    }

    if (cached_character_controller != null) {
        cached_character_controller.enabled = true;
    }

    if (cached_third_person_controller != null) {
        cached_third_person_controller.enabled = true;
    }

    if (cached_animator != null) {
        cached_animator.enabled = true;
    }

    in_ragdoll = false;
}
#

i think i got my ragdoll to work o.o

eager steppe
#

How do I make numbers line up in my leaderboards?

#

It took me a bit of reading to see this isn't a bug, but rather my score simply just has less numbers that require a lot of space

somber nacelle
upper pilot
#
CombatActions = CombatActions.OrderByDescending(i => i.Move.MoveSO.Priority).ThenBy(i => i.Character.Attributes.Speed).ToList();

Doess the .ThenBy sort in descending order or ascending in the above example?

somber nacelle
#

considering there is a separate ThenByDescending, i'd assume it sorts in ascending order

upper pilot
#

makes sense

karmic brook
#

Yeah it sorts in ascending order on default

upper pilot
#

Ah there is ThenByDescending 😄

upper pilot
#

Error:

NullReferenceException: Object reference not set to an instance of an object

When debugging the above line everything seems fine, until `.ToList) I think

#

So I am getting Speed of character

#

This line:

        CombatActions = CombatActions.OrderByDescending(i => i.Move.MoveSO.Priority).ThenByDescending(i => i.Character.Attributes.Speed).ToList();
fervent furnace
#

dont use (one line) lambda expression and debug inside?

upper pilot
#

How can I change this to multi line?

#

The idea is to sort moves by their priority, but if the priority is same then by character speed

fervent furnace
#

()=>{statements; return value;}

upper pilot
#

i.e. Move priority -1 and -1 would be sorted by character.speed

fervent furnace
#

btw you can have a custom comparator then just inplace sort

upper pilot
#

I dont know how to make it work with what I need other than making a list for each priority then combine those sorted lists.

#

FireBall: Priority 1, CharacterSpeed: 10
IceBall: Priority 1, CharacterSpeed: 5
MetalBall: Priority 2, CharacterSpeed: 1

Priority: MetalBall, FireBall, IceBall

latent latch
#

just gotta code your whole project on one lambda line

fervent furnace
#

i know, Icomparator can sort the list in any order you like, since you have full control on the return value

public int cmp(type a,type b){
  if(a.priority==b.priority){
    return a.speed-b.speed;
  }
  return a.priority-b.priority;
}
upper pilot
#

Does it work with negative values?

#

Because Priority can be between -3 and 3

fervent furnace
#

-3-3 is -6

#

usually cmps return negative if the first one "less" than second one

upper pilot
#

Found the error with my code, for w/e reason it was setting Character to null.
If the previous solution works then I'd keep it

swift falcon
#

For some reason, my sprite is not showing on the screen in unity 2d. Any ideas?

#

im talking about "player"

somber nacelle
#

Not a code issue. It's too close to the camera.

swift falcon
#

thought about that

#

how could I fix

somber nacelle
#

Put your camera at -10 on the z axis and everything else at or above 0

swift falcon
#

all axis?

somber nacelle
#

Oh actually it's not too close to the camera, it's nowhere near it

#

It looks like it's on your canvas for whatever reason

knotty sun
#

Why do you have non UI objects as children of the canvas?

swift falcon
#

got it out of the canvas

#

still nothing

#

oh got it

somber nacelle
#

Did you also move it to where the camera is actually at?

swift falcon
#

camera is that small rectangle at bottom-left

#

imma just make my sprite an image

somber nacelle
#

Your ground shouldn't be on the canvas either and if you go trying to use UI objects for this you're gonna have a bad time

swift falcon
#

alright

upper pilot
#
    public int Defense
    {
        get { return (int)(((float)CharacterSO.BaseDefense + (float)_Defense) * (Character.HasStatus(StatusEffect.Restrained) ? 0.5f : 1f)); }
        internal set { _Defense = value; }
    }

Looking for recommendations.
Should I store defense/base defense as floats to make the above cleaner or is there a better way?