#archived-code-general

1 messages · Page 295 of 1

rocky jackal
#

so i could just use that instead of the normal ?

hard viper
#

not exactly, but you can definitely use this information especially to figure out where on the collider you should count as being

#

again: .Distance can tell you if mario should count as being on top of the goomba or at its side

#

so if you need to know if the monkey hand is supposed to be gripping a ledge, that is a good use case for calculating penetration

#

.Distance also gives you a unique point of the colliders along that line that would be in contact once displaced

rocky jackal
#

i dont think you understood what im trying to do

#

isnt vector3.idtance just the distance between two points ?

hard viper
#

i’m talking about Collider2D.Distance, which is equiv to Physics.ComputePenetration

#

Collider2D.Distance has absolutely nothing to do with Vector2.Distance and Vector3.Distance

#

Collider2D.Distance and Physics.ComputePenetration take in two colliders, and output the minimal translation vector to get them to be in contact exactly.

#

unlike contact points, these two methods (for 2D and 3D respectively) give a unique vector and point of contact to work with

#

you need to generate a unique result (ONE normal) to work with. And it needs to be an actual normal on the shape.

wet briar
#

Hi, I have a project in Unity 2022.2.6f1 . I am trying to make a Roslyn DiagnosticAnalyzer work with additional .resx files. I was advised to provide those in our csc.rsp file since the project has multiple .csproj files, in the form of -additionalfile:"Assets/path/to/the/file.resx". However, if I do this, while there are no compile errors according to Unity and the analyzer does work on the codebase, somehow no scripts are attached to any prefabs or scenes anymore. Any advise? (not sure if this belongs here, or in #archived-code-advanced, or somewhere else ThinkTriangle )

runic nimbus
#

My magazine and gun both have rigidbodies on them and that is clearly causing problems
I was hoping making them kinematic would make them play nice but..
I don't want to use layers to fix it. How else?

leaden ice
dense tapir
runic nimbus
#

Yet it stays in the same spot, strangely

runic nimbus
leaden ice
#

don't mix physics/non physics motion

#

When you put the mag in the gun, make the rigidbody kinematic

runic nimbus
#

It is.

#

That's why it doesn't fall

#

if I make it physical, both objects do the worm wiggle

craggy breach
#

hello. how get how many pixel is visible in sprite? im using masks and need the visible pixels percentage

#

int totalPixels = image.GetComponent<SpriteRenderer>().sprite.texture.width * image.GetComponent<SpriteRenderer>().sprite.texture.height;
Texture2D maskTexture = image.GetComponent<SpriteRenderer>().sprite.texture;
Color[] maskPixels = maskTexture.GetPixels();
for (int i = 0; i < totalPixels; i++)
{
if (maskPixels[i].a > 0)
maskedPixels += 1;
}
print((float)maskedPixels / (float)totalPixels * 100f);

#

im using this now but not work

tawny elkBOT
leaden ice
#

also pixels in the sprites don't correspond to pixels on screen

#

It would be better probably to do this with a shader

#

output a texture and count the white pixels for example

dense tapir
#

hey guys?

my PlayerStats and Experience is finish now...
but now iam tested it inGame...it works fine, but have a little issue:

if there added in short time XP...then the calculator dont work correctly...

he use then the current value from this add, not the target value from last add...
(if i wait to finish the last add, then it works fine)

clear halo
#

Hi. I want to make a card game. The properties of each card is stored in a scriptable object. I want to attach the abilities there as well but I can't attach scripts. Is there a workaround for this?
The Scriptable Object:

using System;
using Unity.Netcode;
using UnityEditor;
using UnityEngine;


public class ScriptableObjectIdAttribute : PropertyAttribute { }

[CreateAssetMenu(fileName = "New card", menuName ="Card")]
public class Card : ScriptableObject
{
    public string cardName;
    public string ability;

    public Sprite art;

    public int cost;
    public int power;


}
dense tapir
dense tapir
clear halo
#

yes

dense tapir
#

whait a second, i haved this problem in past too, i look how i have solve it

leaden ice
#

You mean MonoBehaviours?

#

Those can only be attached to GameObjects

dense tapir
#

public List<string> additionalScriptNames; // Liste der Namen der zusätzlichen Skripte

// Zusätzliche Skripte hinzufügen
            foreach (string scriptName in additionalScriptNames)
            {
                Type scriptType = Type.GetType(scriptName);
                if (scriptType != null && typeof(MonoBehaviour).IsAssignableFrom(scriptType))
                {
                    enemy.AddComponent(scriptType);
                }
                else
                {
                    Debug.LogWarning("Skript \"" + scriptName + "\" wurde nicht gefunden oder ist keine MonoBehaviour-Klasse.");
                }
            }

spring creek
#

```

clear halo
dense tapir
leaden ice
#

then instantiate the prefab as a child

dense tapir
dense tapir
hexed oak
#

Was able to get my single sound effect randomizer working that changed the pitch/volume of the sound effect to make it seem like there were more than just 1 sfx. It created a new AudioSource for each sfx playing--which created a lot of garbage, so I implemented object pooling for it and now it seems to work well

void turtle
#

What depenceny injection packages/libraries are recommended nowadays? Most solutions I found were not updated for years

spring creek
#

Extenject and Zenject are the two most common I see.
Mostly people just roll their own though afaik

rain minnow
fleet matrix
#

I am trying to create a save and load of the PlayerData but I am experiencing difficulties can anyone guide me ?

#

!code

tawny elkBOT
fleet matrix
#

!bug

tawny elkBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

fleet matrix
#

!logs

tawny elkBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

rigid island
surreal cloak
#

if i have a game object name of a game object i have to destroy. How do i find that game object in the list by its name.

clever lagoon
#

^he does not recommend it because it is generally considered best practice to keep REFERENCES to objects, rather than finding them by name, for performance reasons.

rigid island
#

not only perfomance but its also very very brittle

ocean hollow
rigid island
hexed oak
#

but what if one frame loses a reference to my variable! It's sooo much better to run GameObject.Find("MyObject") in the Update() loop so that it will never lose the reference 😄

ocean hollow
#

what if the sound gets lost along the way?

hexed oak
#

exactly, and since my pocket tangles my headphones anyways, I pre-tangle them before putting them in my pocket

fleet matrix
ocean hollow
fleet matrix
#

platform have 2d box collider is on Trigger

ocean hollow
#

how do you have it setup in your scene? is the player on the elevator instantly after play?

fleet matrix
#

wait

ocean hollow
#

so the problem is that the elevator isnt going up or the player isnt being parented?

fleet matrix
#

movement is lateral

ocean hollow
#

what about your debugs?

#

are they called?

fleet matrix
#

? i don't have error in the logs

ocean hollow
#

your debug.log statements in your funcs i mean

#

Debug.Log("Player Entered");

fleet matrix
#

doesn't write either

ocean hollow
#

then its a collider detection issue

fleet matrix
#

I have a collider box in trigger another one without trigger and a rigid body in kinematic are all 2d

ocean hollow
#

either your player doesnt have the player tag or you colliders are setup wrong

#

those are the only options

fleet matrix
#

player have tag Player for colliders i don't know

upper pilot
#

How would you generate a random int that is max inclusive without adding +1 to the max?
Say, I want random between 1 and 1 or random between 1 and 3.
First should return 1, second 1, 2 or 3.

#

Random Range is max exclusive for ints

hard viper
#

why would you not just add 1

#

it’s an int. this should not be complex

upper pilot
#

you are right I think 😄

#

just tired

lean sail
upper pilot
#

I knew this had to be simple since google had nothing for inclusive int,int random lol

indigo verge
#

Following a tutorial on inventories, but I can't figure out how to make this accept the eventData from the OnDrag event using the new input system. Can anyone help with this?

#

I'm struggling to figure out what exact syntax it's wanting, for me to add the pointer info that it needs to function.

#
    public void OnDrag(GameObject obj, PointerEventData eventData)
    {
        if (mouseItem.obj != null)
        {
            mouseItem.obj.GetComponent<RectTransform>().position = eventData.position;
        }
    }
#

And here's the function that that line is associated with

indigo verge
#

https://www.youtube.com/watch?v=ZSdzzNiDvZk&list=PLJWSdH2kAe_Ij7d7ZFR2NIW8QCJE74CyT&index=5

Also, if it matters, here is the tutorial I am trying to follow to create my inventory system (though I'm using a list of structs instead of a dictionary, due to some behavior I didn't want)

Item swapping with #unity3D is the 5th part of my Inventory System playlist using Scriptable Objects!

Source Code: https://github.com/sniffle6/Scriptable-Object-Inventory

If you like this channel, or just Unity in general, consider joining my Discord at: https://discord.gg/5yj4Ecp

*************************************************************...

▶ Play video
#

Any help with this would be deeply, truly appriciated.

indigo verge
dense tapir
rain minnow
tawny elkBOT
normal basin
#

Hey is there any reason why it cannot find the folder in my Desktop? Is there some sort of access rights?

sleek heath
dense tapir
#

ye if i make cs
then discord say me its to large

rain minnow
sleek heath
rain minnow
normal basin
dense tapir
sleek heath
dense tapir
#

and the animation isnt the problem...

just the calculate if i add in short time few times of XP

buoyant scroll
runic nimbus
#

So my gun has a bunch of colliders, and my magazine has a bunch too. When I insert, it makes the whole thing freak out cause 2 rigidbodies are in eachother. How fix?
I don't want to use layers
There are many colliders and I cant do physics.ignorecollisions on all of them
I just want to make 2 rigidbodies have all of their colliders ignore eachother for some time

ocean hollow
runic nimbus
#

They are independent of eachother.

#

VR btw

ocean hollow
runic nimbus
#

I have never gotten an answer from there.

#

This isn't exclusive to VR so I think it's okay here

hexed pecan
#

And why would a magazine have many many colliders

runic nimbus
hexed pecan
runic nimbus
#

Is that really the best way?

#

Just feels weird

hexed pecan
#

Or just remove the magazine's rigidbody when you insert it

runic nimbus
#

The colliders would still mess with the gun, I think

hexed pecan
#

If you make it a child of the gun then it will be part of the gun's rigidbody

runic nimbus
#

Multiplayer game, can't use parenting

#

Well, if there's no other way, then I'll do the combination thing

mighty tide
#

they just do it using physics

high summit
#

Seems like an important part of hierarchy to not have access too

zenith valve
#

Hi people 👋 is anyone experienced with unity version control. I’ve set up a project with my collaborator but whenever he downloads the project on his end the folder is empty,
could I have missed a step? Please advice if you know. Thanks

spring creek
merry stream
#

so i'm making an ability system similar to GAS in unreal and am having issues coming up with a way to deal with "reverting effects." So like a temporary slow, or something like that. Any suggestions?

zenith valve
merry stream
#

... making it in unity, similar to GAS in unreal

runic nimbus
#

Whereas with regular values like floats and vector3s, they can be simply saved and stored in a previous state

#

Not so much with one way actions like parenting

high summit
#

Suddenly multiplayer sounds much more daunting to set up

#

how do you handle simple things that normally use parenting such as moving platforms though

runic nimbus
#

Dude, it sucks. Multiplayer is the hardest thing you can do in game development.
But it's all worth it, nothing beats playing a game with your own players

high summit
#

The first game I’m trying to make is meant to be a multiplayer game so I’ve been trying to future proof all my code for when I implement it

runic nimbus
runic nimbus
#

So I would suggest dedicating this to learn as much as you can about Unity and C#, then starting fresh with some multiplayer samples to learn networking.

high summit
runic nimbus
#

To be clear, you can use parenting in multiplayer, but most modern networking libraries do this thing called prediction, you can see it in action in multiplayer cause your character moves before getting a ping back from the server. Your client is predicting that it can do this, so it does it locally first to give the user a very sharp response.

late lion
runic nimbus
#

What happens with parenting, is you need to specifically tell Fusion that if something goes wrong, you need to unparent it to roll back

#

I just found moving objects regularly to be less of a headache

high summit
runic nimbus
#

Oh well yeah, cause there's no case where that could go wrong. Everyone needs to generate that dungeon on their client.
It's only a problem if there's a chance that the situation is different on the server than on your client, so your client does something impossible and then needs to cancel it (rollback)

rain minnow
high summit
merry stream
#

i have it somewhat working, but it feels hacky

late lion
agile carbon
vocal sorrel
agile carbon
#

Therefore I don’t know where the rear wheels go.

vocal sorrel
agile carbon
#

You turn left sure if ur steering left

vocal sorrel
#

oh i see

agile carbon
#

But your front tires move in the direction of the steering direction

#

But your chassis rotates

vocal sorrel
#

wheels rotate but the car itself does not

#

right?

agile carbon
#

And I need to simulate it

vocal sorrel
agile carbon
#

The car doesn’t rotate to the direction of the wheels

vocal sorrel
#

an object rotating is basically this

#

two vectors

agile carbon
#

Yes

vocal sorrel
#

your forward vector

agile carbon
vocal sorrel
#

and you add a sideways force to that forward vector

agile carbon
vocal sorrel
agile carbon
vocal sorrel
#

or maybe you could just cheat your way out and rotate the car itself a small amount, causing the car to steer like it should

vocal sorrel
cosmic rain
#

When a force is applied at different direction on 2 different points of an object(presumably on different ends from center of mass), it would rotate.

vocal sorrel
#

yes

cosmic rain
#

Think of a needle of a compas.

agile carbon
#

That’s a thing?

vocal sorrel
#

yes

agile carbon
vocal sorrel
#

think of it as when you rotate a valve

cosmic rain
vocal sorrel
#

wait, that exists?

#

good to know

agile carbon
#

Then I won’t need to calculate rear position because it’s a child

#

🙏 PEAISE RHE FODS

cosmic rain
grand bobcat
#

https://gdl.space/reqarehoxa.cs
For some reason whenever this code is run it crashes at a certain point that seems to be different every time. Im not sure why. A very similar but slightly diferent verison of the script worked just fine, and ive made sure it isnt any of the scripts that this references, so im not sure what the error could be

cosmic rain
grand bobcat
#

"application is not responding" followed by it closing

#

so an actual crash

cosmic rain
grand bobcat
#

i thought that too but i cant see a reasaon for it to be if it is

cosmic rain
#

Since you're asking in code general channel, you should know how to use a debugger, so use it when the freeze occurs, to see what the code is doing.

grand bobcat
#

Got it 👍

#

will try

lean sail
twilit scaffold
#

I have found a C# course that is working for me. Perhaps it will help others too. I have to play at min 1.5 speed though
https://www.youtube.com/watch?v=DSbgl48VFLg&list=PLJitdQVsSaf7nHcznVnW7ALB2K514QKk_

If this course helped you, please click the THANKS button and help support our channel! It took many many weeks to create and edit!
Your THANKS comment will be highlighted so that everybody can see how awesome you are!
Thank you! :)


Hello! Welcome to C# Programming for Absolute Beginners!
Here you can learn C# from absolute basics...

▶ Play video
dense tapir
# rain minnow i just took a look. `elapsedTime` is used incorrectly for the lerp, and it seems...

what you mean with "i use elapsedTime incorrectly"?

and why should the coroutines overlapping each other? the first coroutine will stopped if not lvl up, and start the second if lvl up...

they never can overlap each other...(assuming I only start 1 process to add XP)...if i start a second then sure, but thats the question, that is what i ask here...

so now i need ask a second question...

thanks that you want to help me...but how you help me if you explain (just with other words) the problem what i explained before?

So I'll explain it again so that the last person understands what I'm explaining instead of trying to explain it again without helping me😪

If I only do 1 process to add XP then it works fine! without problems!
But if I start several processes to add to XP in a short time, and then

e.g. from process1 the XP should go from 30 to 50...
and at 40 another process is started, then not the 50 + new process, but 40 + new process is calculated... so always the value at which the currentValue is currently in the change process, instead of the value where the currentValue should go...

hidden compass
#

Use the proper method to paste !code plz.. mobile guys see this

tawny elkBOT
mighty tide
hidden compass
#

Ya. We have to download the file and go find it to open it..

mighty tide
#

bet if change the object to a list with a wheel class it would do better

hidden compass
#

Ya looks decent. Covers the basics.. A list or array would def clean it up a bit.. I use two arrays 1 for the rear wheels bc sometimes I like them to do something different

agile carbon
#

I’m not using wheelcolliders btw

hidden compass
#

I made mine with a big sphere collider.. like a hamster ball

mighty tide
agile carbon
#

Also there is no steering in that script

mighty tide
#

yes there is

spring creek
hidden compass
#
    private void HandleSteering() {
        currentSteerAngle = maxSteerAngle * horizontalInput;
        frontLeftWheelCollider.steerAngle = currentSteerAngle;
        frontRightWheelCollider.steerAngle = currentSteerAngle;
    }```
agile carbon
hidden compass
#

Lol phone slow

agile carbon
#

I appreciate the help but unfortunately it won’t help with the project

spring creek
agile carbon
hidden compass
#

From way up there

spring creek
hidden compass
#

Realism is wheel colliders or a form of them.. Arcade kinda just translates and the wheels are more just graphics

#

Wheels should be child of car anyway and should roll with the chassis

agile carbon
#

I think I’ll use a rigidbody in the chassis

hidden compass
#

Make a hover car

#

Add wheels later

agile carbon
#

And apply forces at specific parts of the car causing rotation

hidden compass
#

That'll work

#

Axle points

agile carbon
#

Yes

#

And I’ll code the wheels myself

#

Including slip and stiff

#

And also calculating steering angle

#

Cause ima do ackermann steering and I will need to code differentials

mighty tide
#

have looked a unity's source code

hidden compass
#

lol, no wheel colliders

mighty tide
#

bouncy

hidden compass
#

just axle points and math

agile carbon
hidden compass
#

never got it to drive good tho

#

too slippery w/o wheel colliders.. and i never wrote any friction forces

agile carbon
hidden compass
#

ya, its just applying upwards forces at each sphere u see

agile carbon
#

Friction

#

I just used circumference of wheel to tackle distance

#

And will eventually apply slip

hidden compass
#

basically a hover car

hidden compass
#

if i go back and add some slip / grip to the points where the raycasts hit the ground (but apply it to the car) it'd feel alot better

agile carbon
#

Roblox makes it too easy dawg

hidden compass
#

good luck on the car..

agile carbon
#

Wheels work on the ground too easily

agile carbon
hidden compass
#

car controller and character controllers always eat up so much time trying to get them to feel good

agile carbon
vocal sorrel
#

a player may just quit playing just because controlling something just feels weird

mighty tide
hidden compass
#

not yet.. since the car floats there really wasnt a need yet

#

i just apply forces and torque to the floating collider

agile carbon
hidden compass
#

physics material

mighty tide
hidden compass
agile carbon
hidden compass
agile carbon
#

And I don’t know why

#

And I wanna make it better

hidden compass
#

been perfecting mine since 2020 ;D

noble mica
#

What do you guys think is better for shooting projectile bullets:

#

_rigidbody.velocity = transform.forward * speed;

#

_rigidbody.MovePosition(transform.position + Vector3.forward * (_projectileSpeed.Value * Time.fixedDeltaTime));

hidden compass
#

i use the first one.. can't say which ones better

agile carbon
hidden compass
#

grabs it in Awake() i imagine

noble mica
#

yep

hidden compass
#

first method looks alot easier too..

noble mica
#

I was getting alot of of shooting in one position rather than using velocity

mighty tide
noble mica
#

Yeah

#

private void Awake()
{
_rigidbody = GetComponent<Rigidbody>();
}

hidden compass
#

GetComponent<Rigidbody>().AddForce(transform.forward * force,ForceMode.Impulse);

noble mica
#

I was told Addforce might be a bad idea doing a top down shooter

hidden compass
#

maybe

rain minnow
#

Depends on the person and how they code their movement . . .

noble mica
#

I just looked it up Velocity moves the object at a constant rate vs Addforce only pushes it which has a way of stopping at some point

hidden compass
#

even on a top down shooter

hidden compass
#

no gravity and no drag

#

he infinite bullet

hidden compass
agile carbon
spring creek
hidden compass
noble mica
#

I see so using gravity would be better to use addforce to simulate gravity within bullets

agile carbon
noble mica
#

What about moveposition

hidden compass
#

ive only ever used moveposition on a character type rigidbody

#

never on a bullet.. so idk

noble mica
#

Yeah I used it for moving too but it also ended up jittering

hidden compass
#

crank up thta interpolation 😅

mighty tide
#

working on a checkpoint system

spring creek
hidden compass
#

addforce with no drag/gravity, or velocity = i think are u two best bets

noble mica
hidden compass
#

addforce would def be more realistic

#

would slow eventually and add bullet drop

spring creek
mighty tide
hidden compass
#

is that Rider ?

mighty tide
#

is free for preview

noble mica
#

Just so I make sure.
Velocity - for constant movement
Addforce - for more realistic bullet movement
MovePosition - For more character based movement

agile carbon
hidden compass
spring creek
hidden compass
#

i used Impulse in my example.. so its all the Force at once

agile carbon
#

Holy fuck @hidden compass I remember you

#

Holy ceap

spring creek
#

The last two are for dynamic bodies only, meaning you HAVE to do MovePosition or rb.position = for kinematic

agile carbon
#

Ur username just rung something in my head

mighty tide
agile carbon
#

Like a year or two ago you just started out

hidden compass
#

ya, its going on 3 years or so now

agile carbon
#

Lmao that’s funny

hidden compass
#

still hanging in there 😄

agile carbon
hidden compass
#

as long as u dont forget too much between, lol

noble mica
#

Appreciate it guys

agile carbon
agile carbon
mighty tide
hidden compass
#

namespaces are like collections/groupings of code that are related

mighty tide
#

helps speed up compile times

agile carbon
#

Ah ok

hidden compass
#

Utils is a decent example

agile carbon
mighty tide
#

yup

#

i have 4

#

keeps things clean

hidden compass
#

i have a few

#

mine arent in folders tho 😬

#

they're just scattered everyhwere

mighty tide
#

it also cleans up my solutions

#

i would marry assemblys

quartz folio
#

namespaces and assemblies are unrelated

hidden compass
#

ya, my ide doesnt even sort with namespaces (i havent figured out how to yet)

quartz folio
#

Namespaces are just handy organisational groups that make it clear how things are differentiated

hidden compass
#

assembs, yea

quartz folio
#

Assemblies are functionally separated groups of code that can compile differently for different platforms and define relationships with other assemblies

mighty tide
#

namespace is the grouping

quartz folio
#

Nope. What you're seeing are assemblies.

Namespaces are like last names, if you have two dudes named Tom then you can tell them apart by their last name.
Assemblies are like families, you can have hierarchical relationships between different families, but it has no real bearing on somebody's name, and the only connection between that and namespaces is that it's convention for people in the same family to have related last names.

vocal sorrel
#

it feels like i am a kid learning again

#

does unity have any built-in timers? or do i have to just substract delta time over a float?

mighty tide
hidden compass
#

had to look up Fleet

#

looks like JetBrains version of VSCode

spring creek
#

And async

vocal sorrel
#

like, for example

spring creek
quartz folio
# hidden compass looks like JetBrains version of VSCode

It kinda is, but it's got more of a focus on cloud integration. Sadly when I tried it about it year ago it was really bad, but it's probably improved since then
Part of why I like Rider is that it just works, and it works well—which Fleet absolutely did not

vocal sorrel
spring creek
#

You would then restart ut where it was

#

Or you could possibly have a bool to prevent it from "running" while it loops doing nothing

#

Like an early return, but just yielding

vocal sorrel
#

i see

#

guess i have to try

hidden compass
#

funny little promotion image.. could u imagine? "hey bro get off my line!"

lean sail
#

i was looking at implementing IDisposable on my Items (poco), so they can destroy an instantiated SO when needed. This SO is instantiated in the ctor, initially I destroyed in the dtor but apparently the dtor isn't always called.
From what i see online, it looks like im required to call Dispose myself. Is there some way to have it automatically called when its not referenced by anything? Right now im concerened about in the future, if one class ends up doing

public void MemoryLeakSimulator() 
{
  new Item();
}

Ill have an instantiated SO just sitting around with no way to destroy it myself

#

I was planning on using a poco instead of the SO, but im still curious if such thing above is possible to solve.

quartz folio
#

Is there some way to have it automatically called when its not referenced by anything?
No. Only the dtor, which you generally shouldn't use

lean sail
#

I guess my solution is either guarantee i dispose everywhere, or not use SO here still then. Thanks

craggy veldt
#

if it was just a plain c# (non-unityobject) we can do this GC.Collect() and then check WeakReference.IsAlive then again who's in their correct minds would do that 😂

lean sail
craggy veldt
#

I'm not sure the side effects are due to you have a reference to unityobjects in there

#

also it's not worth tho, gc.collect is slow af

quartz folio
#

Sadly you should just call Dispose, that's how it's intended to work

#

Just as you should call Destroy on any UnityEngine.Object types you allocate (even those allocated by material calls)

craggy veldt
#

yeah, even if it's just a plain c# class, weakreffing has a limitation once it's successfully being weakrefd, you can't keep it for a long period of times due to it might be promoted to gen2.. also not sure if gen2 stuff exists in il2cpp

lean sail
#

Yea ill just rework this so i dont instantiate an SO. Then Item gets destroyed, and the poco inside will also be destroyed i believe.
I've never really looked too deep into gc or memory stuff works so this has been pretty eye opening

quartz folio
#

No managed memory is released until all references are null

#

and UnityEngine.Objects aren't released unless Destroy is called, or a complete scene reload occurs, or Resources.UnloadUnusedAssets (which is very expensive)

#

to be clear, UnityEngine.Objects have native and managed parts, and so Destroy doesn't release the managed part

#

For example, with a reference to an SO that has a reference to a managed object, calling Destroy releases the native memory and the SO will evaluate to null, but the managed SO and its references are still in memory until you also set the reference to the SO to null

vocal sorrel
#

how do i change a single color from a color block?

#

do i need to make a new color block and the nreplace the original one?

latent latch
#

ye

vocal sorrel
#

oh

#

ok, thanks :)

spring creek
vocal sorrel
hidden compass
vocal sorrel
#

selectables seem to have it according to unity docs

rigid island
#

you replace whole thing iirc

spring creek
vocal sorrel
lean sail
burnt crypt
#

Any linux devs here?

dusk apex
burnt crypt
#

No I'm just here to flex

#

I just wrote a pointer scanner for linux

rigid island
burnt crypt
#

Literally the very first one on linux

#

Which makes reverse engineering (and cheating) on linux games substantially easier

craggy veldt
warm wren
burnt crypt
#

I just made the tooling way better

burnt crypt
craggy veldt
burnt crypt
#

Thats true

#

Its still cool asf

craggy veldt
#

😅 I don't understand this

leaden ice
#

Congratulations here's your duck 🦆

burnt crypt
#

Ty hehe

compact spire
#

I'm not finding much on dependency injection and it's practical use cases in Unity, is it just not used very much?

#

Trying to sort out how it fits in with delegates/scriptableobjects/monobehaviors

latent latch
#

I once used ghidra so technically im pretty much hackerman too

burnt crypt
#

Was really funny seeing the gamedev course guys at my uni do this to their unity games

craggy veldt
#

you can brag about it once you're done

burnt crypt
#

Ew microsoft

#

I'll be honest you guys are safe because I don't want to touch c# with a 10 foot pole

#

Stack machines can btfo

craggy veldt
#

aight you're just trolling in here

hidden compass
burnt crypt
#

Complaint

hidden compass
latent latch
#

Dependency Injection though is pretty much the concept of object pooling

burnt crypt
#

And I don't mean that it uses stacks for control flow, I mean that the c# virtual machine literally doesn't have more than like 3 general purpose registers

#

Which is aids

compact spire
#

wait, what does object pooling have to do with dependency injection?

hidden compass
#

heres what that article covers.. its the most decent one ive seen so far

#

altho i dont know nothing about it tbh, just searching for ya

compact spire
#

@hidden compass Yeah that might have some of the information I'm looking for, I wasn't having the best luck on youtube.

hidden compass
#

found it in a reddit post (screenshot from part2) of that article

latent latch
#

Say you want to spawn an enemy with gun and bullets:
step 1: Dequeue EnemyMono
step 2: Dequeue GunMono
step 3: Dequeue BulletMono

#

attach em together, and bam dependency injection

#

technically all monos could be considered dependent on injection cause you don't have access to a normal constructor

compact spire
#

Yeah that was one of the things I was trying to figure out, since they seem to overlap a bit.

burnt crypt
#

Do you guys ever use non-OOP programming paradigms or is it infeasible for gamedev?

compact spire
#

what like functional programming?

latent latch
#

oop is pretty bad alone

burnt crypt
#

Yeah

latent latch
#

you need ECS or compositional approach to really have a manageable workflow

compact spire
#

I mean you could, but from what I understand is that disregarding OOP for 100% functional programming seems like a bad idea.

burnt crypt
#

Ngl, the fact that you guys have to consider design patterns this seriously is really cool

compact spire
burnt crypt
hidden compass
#

much

hidden compass
#

ECS is over my head

latent latch
#

OOP you can dig a hole pretty easily if derive your behaviours too deep, or spread too thin

burnt crypt
compact spire
#

ECS is black magic I don't have the inclination to understand

#

It's hard enough I keep replacing everything I'm doing over an dover.

#

I got halfway through converting to use a service locator, now I'm on to DI

spring creek
burnt crypt
latent latch
#

With OOP you can fall into problems such that you have like an enemy
Orc -> RangeOrc
-> MeleeOrc
-> MagicOrc

But now the question is what if you want your orc to melee and be range? Do you make a MeleeMagicOrc? And this is the problem with OOP alone.

compact spire
#

@spring creek Conceptually I kind of get it, and I've looked at some demo's of how it's setup, but writing something around it is a whole other pickle

spring creek
hidden compass
#

i just re-iterate and try to plan out my projects so i dont have to worry about that Orc issue

latent latch
#

Right, c# you have interfaces instead of that, but even then you can run into the diamond problem of multiple inheritance

compact spire
#

It's too different than what I'm used to, Unity is hard enough when coming from something like a simple backend service.

cosmic rain
#

Gamedev is hard.

hidden compass
burnt crypt
#

Guys that make game engines are just as insane if not more insane than OS devs

high summit
#

Is FishNet the general consensus for setting up multiplayer?

cosmic rain
#

No

burnt crypt
#

FishNet?

compact spire
#

FishNet? is that new?

hidden compass
#

ive heard about that here recently.. didnt know what it was

burnt crypt
cosmic rain
#

There is no general consensus. Use whatever fits your project

high summit
#

Doing a little research right now and seems like Mirror was the previous one typically used

burnt crypt
#

Is it the 'correct way' to use c#?

high summit
#

seems like FishNet is new

hidden compass
#

Mirror is easy to set up.. Lobby's Connections and stuff

latent latch
burnt crypt
latent latch
#

because Unreal forces blueprints and that's a job of its own

hidden compass
#

unity is a prototyping beast

burnt crypt
#

Unrelated to the thing I replied to but still hoho ^-^

high summit
burnt crypt
cosmic rain
compact spire
#

I think Photon is one of the more popular options for Untiy

#

for multiplayer

burnt crypt
#

I had to use java for the first time in yearssss recently and it kind of hit me how namespaces are just a default that you don't question

#

Or these fancy ass build systems

hidden compass
#

all of those mentioned that ive seen use their own servers to host games.. not sure about having one of hte players be host..

#

not sure what solution fits there

compact spire
#

so you are looking for something that supports peer 2 peer?

latent latch
#

Fishnet is aight, but their documentation is a little arse. I do think Unity's networking library is probably one of their best modules and a great starting point despite behind on some features.

burnt crypt
#

Do you guys write your own protocols for online play

cosmic rain
burnt crypt
#

Or use libraries that come with a framework that you just fill out

hidden compass
cosmic rain
#

They might be using lobby servers for establishing the p2p connection though

hidden compass
#

ahh perhaps..

cosmic rain
latent latch
hidden compass
#

TIL

cosmic rain
#

Because it's generally impossible to host a server normally via home internet.

burnt crypt
#

router will kill all incoming conn requests

compact spire
#

Wouldn't be using P2P only be difficult due to network shenanigans like NATs, or is that not really an issue to think about?

burnt crypt
compact spire
#

I see

cosmic rain
#

Though, I guess that depends on the framework

#

With photon I think all the traffic goes through such a server

burnt crypt
#

Mom can I port forward pleaseee

#

Pleaseeee

#

👉 👈

hidden compass
latent latch
#

best documentation unity has put out

#

because there's actual tech docs that explain to you the process of it all

hidden compass
#

i might give this a try.. just to add a MP prototype to my list.. its been a while.. since I made a photon lobby / MP walking sim

latent latch
#

so much effort placed into this it's unreal (I made pun teehee)

hidden compass
#

lol.. 😄

#

ya, all their docs need to look like this

#

pinned on Github now i just need a mp game idea 😅

dark kindle
#

speaking of docs, i want to know how everyone documents their code for their games? what tool is best to use? a wiki?

compact spire
#

documents their code?

dark kindle
#

yes, like if i work on another project i want to come back and still remember how thing work

compact spire
#

write readable code, or if that fails, write comments

dark kindle
#

yes, but maybe show screenshots of gameplay and what objects in screen is associate with code.. i cant embed screenshots in code, can i? unless i can embed links in c# or if i hover over a certain code a screenshot appear

compact spire
#

That is a bit far

dark kindle
#

thank for input though

compact spire
#

Generally if you take the time you name your variables/classes/methods ect in a way that will make sense to future you

lean sail
compact spire
#

and you don't make a bunch of monolithic hunks of code, it should be readable.

west sparrow
#

For some projects, if there is an API, I'll use doxygen and uml. But that's pretty rare.

I usually have a Readme in the project for the team, so when they grab a template from our repo, there is help getting going.

For bigger projects we do use an internal wiki. But I've been pushing the team to keep it to the readmes so they are versioned.

dark kindle
west sparrow
#

In my case, I have some very thorough all in one templates (especially in VR). So having a gentle reminder of how to setup something is always a plus.

dark kindle
#

thank, that soudn good

west sparrow
#

It's also helpful to document how to deal with odd VR frameworks that need special toggles and such. But wiki & readmes.

At the top of your code it's helpful to use /// three slashes for proper documentation. Then if you do need to, you can use doxygen later to generate code docs. And keeping it in its own namespace is always a good idea too.

dark kindle
#

it a game engine so maybe i also need to understand myself the configuration, for example game objects, references, ui layout etc., which i may need more than what comment provide

#

sound good

soft shard
# dark kindle speaking of docs, i want to know how everyone documents their code for their gam...

I find establishing some architecture in your code can help with readability later, since if you understand how a certain pattern works, and your code more-or-less follows that pattern, it should be easy enough to follow along your logic later, if you plan on templating your code or turning it into a framework or something open source, then adding summary comments can help for public functions and properties, the downside with comments or wikis, is that they also need to be maintained when code changes or gets refactored, or if you make certain functions, events, etc obsolete, and while working on a project, code changes often from my experience so it can kind of be an additional thing to manage imo alongside source control

latent latch
#

You'd probably want to minimize where the problem is and if it's more network related, take it over to #archived-networking or the photon server

lean sail
#

you really wont get better multiplayer help here. a lot of people here dont even touch multiplayer and wouldnt be able to help you with photon specific stuff

hidden compass
#

Github is another good place to document ur code.. if you learn markdown you can make some good Readme files with images and all that

spring creek
hidden compass
#

Oh abs.. I had to put it aside. I was starting to color code everything.. had an index list of emoji as symbols n all

merry stream
#

how do I conditionally show fields in the inspector, for example only reveal certain ones if a certain enum is set to something

#

I figure its possible with an editor script

knotty sun
latent latch
#

So I've this dilemma on when to remove an object that's contained and managed by another class. When I access this object, should I allow to return the reference and keep the reference contained in the manager? Or should I always remove the reference from the container when it is to be accessed?

#

For example, should I have a method of:

public bool TryGetAndRemoveObjectAtIndex(int index, out Object obj)```
Otherwise, who should be in charge of removing these references from the container if the object is consumed?
chilly surge
#

Pretty much dependent on your usage pattern.

#

And I mean, you can always have both, like Queue<T> has both Peek and Dequeue.

latent latch
#

For instance, an inventory with a health potion. You can access the inventory and grab the reference and drink it -> the object is consumed and destroyed.
Two ways I can see handling this, one being to just remove the health potion as I access it and let the health potion destroy itself, or reinsert it later if it's not to be consumed (and only modified)

#

The other way is the health potion needs to do a callback to the inventory and tell it that it's to be destroyed and remove that reference.

#

Or maybe even let the handler manage the usage of the potion instead?

#

I think the biggest issue is keeping track of references that would be modified, but still be active in the inventory.

#

Perhaps the modification consumes it in the proccess, now I would need to remove it from the inventory x_x

#

Maybe the idea is to just keep all behaviors on the items themselves private and bound by a delegate and let the manager call the Use() methods and such

placid summit
#

how do you manage comments on both interfaces and implementations when you just want them to sync?! notlikethis

latent latch
#

Usually if you stick a comment above methods you do get some of that information when you hover over the methods elsewhere, but im not too sure if that works with interfaces

trim schooner
#

It's not just a comment above a method which will give you info.. it's a particular type of comment. Do three /'s above it and it'll give you the summary comment, which allows you to add the params/ etc

upper pilot
#

Do you have to create all scripts in Unity or only monobehaviors?

#

So Unity creates meta files

#

Which afaik are needed for things like showing script in the inspector

trim schooner
#

The meta file has nothing to do with where you create the script, they automatically get created for everything that gets put into the project.
Don't even need to make a monobehaviour in Unity.

upper pilot
#

We had this issue before

#

Is that not the case?

trim schooner
#

I've never not created them in unity, because.. why wouldn't you 😄

But I don't see why it would make a difference.. Unity auto creates a meta file for everything in the assets folder

#

Just tested it, created a new class in VS.. saved as into my Unity projects scrips folder.. meta file is created, as expected.

tardy crypt
#

Me every time I add a feature in my game: "whew, got it working, let's go on to the next thing." Me when I need to change that feature: "wtf was I doing, I have to rewrite this whole thing."

heady iris
#

So if you create a script outside of Unity and don't let Unity reload (I have auto-reload disabled, for example), then there will be no .meta file yet, since Unity won't have imported the asset

unreal temple
#

I have a plugin that creates the meta file for me too.

#

But it's not necessary. Only thing that matters is the csproj being updated (which the c# plugin does).

upper pilot
upper pilot
#

I have auto reload I think, but I had an issue when creating file outside of Unity

#

People even recommended creating them via Unity here

tardy crypt
#

Looking for some guidance on a problem I'm trying to solve. I have some Monobehavior that needs to be dynamically given "effects" at runtime. The effects change the behavior of either the monobehavior or something that interacts with it. The main way I have been doing this was to just use polymorphism for the effects. In other words, base class "Effect," so the monobehavior stores a list of those effects and then I can add whatever sub classes I want during run time. The effects themselves define behavior of the effect in code. This seems to lead to a large class hierarchy which I kind of want to avoid due to how brittle it is. Is there a better way to implement something like this? TLDR: I want to dynamically give different behaviors to a monobehavior at runtime and I'm wondering if there are simple options other than polymorphism. Should I just make the effects a data store and implement the behaviors as a set of switch statements (say) in whatever components actually use the behavior?

latent latch
#

Composition

heady iris
#

can you give an example of part of the hierarchy you don't like?

tardy crypt
#

ok let me see how to express this succinctly. this is a tile-based game. i have... things that can occupy tiles... let's call them terrain. the terrain imparts effects to the game. the effects that the terrain can have depend on the rest of the environment. so the idea was to have an "effects" class for the terrain and add/remove these effects from the terrain Monobehavior as the environment changes.

#

one example effect is modifying movement of the players' units. another is damaging them. another affects how the player's units can, themselves, affect the terrain.

#

the goal is to have a lot of different effects. i haven't really built these all out yet but i can see issues with overlapping functionality and whatnot. so i guess my question is, is this just a difficult problem that can be solved reasonably with polymorphism or is there an approach that is more amenable to the situation...

heady iris
#

The premise sounds fine to me.

tardy crypt
#

ok thanks for your input.

heady iris
#

One way I've handled this before was to give the effect class a bunch of virtual methods that all do nothing

#

so there's one for OnUnitEnter that you call whenever a unit enters the terrain tile

#

and the abstract base class's method is empty

#

another might be ModifyMovementCost(int currentCost)

#

the base class's method would just return currentCost

latent latch
#

Technically you are doing some polymorphic calls since I assume these effects take in a player ref

heady iris
#

you iterate over all of your effects and run the relevant method

#

most of them will do nothing; a few might actually have an effect

#

The other way would be to add interfaces for each kind of effect

#

not literally every concrete effect

#

but the more abstract ideas like "an effect that can apply to a unit"

tardy crypt
#

so i guess... the idea is that the abstract base class defines the list of possible things that can happen, and the child class determines whether the effects actually happen and what they do

heady iris
#

or maybe "an effect that applies to a unit when you enter the tile"

hard viper
#

I have a very tile-based game. I use ClassTypeReferences to tie the definition of a specific class to an SO. Each tile’s TileBase is tied to an SO with that classtypereference. Different things in code can instance the relevant class to use the code on command.

heady iris
#

Then you'd be filtering your big list of effects by type

latent latch
#

Yeah, my abilities class has like 5 lists and it checks if they are empty or not, but each list can contain similar behaviours.

heady iris
#
foreach (var effect in effects) {
  if (effect is IOnUnitEnterTile enterTileEffect) {
    enterTileEffect.Apply(unit);
  }
}
hard viper
#

My tile SO can also have a prefab tied to it if I need something more involved

heady iris
#

since there are multiple situations where you apply an effect to a unit

hard viper
#

if I use ClassTypeReferences, I make sure to restrict it to classes that implement a specific interface or abstract base class

heady iris
hard viper
#

like my SOs have a few class type reference fields for: ICustomDraw, ConductivityStrategy, and TileMonobehaviour

heady iris
#
List<IUnitEffect> onEnterTile;
List<IUnitEffect> onExitTile;
#

e.g.

#

This is less convenient than just having a single list of all effects that currently apply to the tile.

latent latch
#

Targeting parameters seem pretty common to split with behaviors

hard viper
#

in this case, you can have a ClassTypeReference to a type that is constrained to either implement ITileEffect interface or extend TileEffect abstract base class.

heady iris
#

yeah, since "damage unit", "heal unit", and "give unit a bonus" are all things that need a Unit

heady iris
#

all of these kinds of effects share a requirement to be given a unit

hard viper
#

like ITileEffOnEnter, ITileEffOnLeave, ITileEffBombable, ITileEffBurnable, ITileEffConductive….

#

or whatever

latent latch
#

That's kinda what Ive came to the conclusion of when brainstorming these roguelite games

hard viper
#

then you have a reference to the one type for the type in an SO, and check if the type implenents a given interface

tardy crypt
#

ok so i guess what i'm hearing is... it's ok to have one or more collections of effects that specify functionality in code (whether by being child classes or by being interfaces), and just have clearly defined categories of uses for the effects so you can call them as appropriate in your monobehavior.

hard viper
#

if a tile effect needs any sort of connection between the different behaviours, then it should be one class for a tile with multiple interfaces, so they can cross talk.

latent latch
#

TriggerOverTime, TriggerOnHit, TriggerWhenHit

hard viper
#

if the behaviour is super separate (like in my case, ingame behaviour separate from level editor behaviour), then they should be split

hard viper
#

i strongly recommend using ClassTypeReferences plugin for this, and also making a giant dictionary that links every tile to an SO with actual info

#

Dictionary<TileBase, MySo> is basically mandatory

#

then you can do whatever the fuck you want in the SO to connect game logic

tardy crypt
#

i'm not sure what you mean by that. can you explain further?

hard viper
#

set booleans, enums, class references, etc

hard viper
heady iris
#

I do something similar, except that it's Resources-based.

hard viper
#

when you know you interact with a tile a given coordinate, GetTile gives you a TileBase, which you now need to go get the actual game logic for

heady iris
#

In my case, I have a bunch of classes that derive from Module that add features to my Entities

#

For each class, I create a scriptable object asset (ModuleInfo) that lives in a Resources folder

#

It contains things like localized string references

hard viper
#

you want a giant Dictionary so you can go from TileBase to a permanent asset on disk that tells you wtf the tile does. In this case, a scriptable object

tardy crypt
#

why not just store the SO as a reference in the tile?

heady iris
#

I use the dictionary approach elsewhere, like to look up SO assets by a GUID I've attached to them

heady iris
#

or module, or whatever

hard viper
#

need a dictionary

heady iris
#

in my case, I could add an instance field to Module that holds a ModuleInfo reference

#

but then I'd have to manually assign that for every instance

#

The association isn't per-instance. It's per-type

#

So it doesn't make sense to use an instance field.

tardy crypt
#

hmm... in my case, the tile types are constructed dynamically based on environment.

hard viper
#

yeah, you want to have a separate connection of instance-data, and one big dictionary that makes it easy to query just the base data

tardy crypt
#

the set of effects are combinations of things based on the environment

hard viper
#

i gtg, but fen has u covered

tardy crypt
#

thanks

heady iris
#

Although, it sounds like Loup was describing per-instance information there.

#

i.e. associating a scriptable object asset with each individual tile

heady iris
latent latch
#

dictionary sounds fine

heady iris
#

each tile should just have a list of effects on it, and each effect should have its own configuration in it

tardy crypt
heady iris
#

a DamageUnitsWhoEnterThisTile effect contains the amount of damage to do; it can stand on its own

tardy crypt
#

i kind of already have the infrastructure for this so... i think i'm going to just do this

heady iris
#

You just need to decide between:

  • Every Effect has a crapload of do-nothing methods on it and overrides just a couple of them
  • Effects implement various interfaces, and you filter your effects based on those interfaces
#

for the latter, you could do something a little interesting

#
public class HurtUnitsWhoEnterMe : Effect, IUnitEffect, IOnEnterTileEffect
#

IOnEnterTileEffect could be a completely empty interface

#
foreach (var effect in effects) {
  if (effect is IOnEnterTileEffect && effect is IUnitEffect unitEffect) {
    unitEffect.ApplyToUnit(unit);
  }
}
#

IOnEnterTileEffect doesn't actually specify any behavior at all. It's just a label.

tardy crypt
#

hmm... interesting

heady iris
#

IUnitEffect does specify behavior

tardy crypt
#

i like this idea, i might try it out

#

this might clean things up for me a bit

heady iris
#

I always feel weird when I'm manually filtering types like this

#

Instead of these "tag" interfaces, you could just have a way to ask an effect if it applies in a certain situation

#

where "situation" is an enum or something

delicate flax
#

sorry to those of you already in the know. but I just realized you can inline assignment in c#. 😅
so you can write this, as opposed to that. works for function calls to.
it's only a syntax thing, but figured I'd share for those of you that are like me and prefer to get rid of that extra line of code 😄

tardy crypt
#

right... that makes sense as well...

latent latch
#

I'm more of a stick to a single class and declare everything but check at runtime via enum (or instantiate the lists of behaviors and who cares if they are populated or not)

heady iris
#

oh yeah, = returns the assigned value or reference

#

which usually just causes confusion when people use it instead of ==

#

compiler warning for every time you discard the value returned by =

#

⚠️ 9999

tardy crypt
#

anyway thanks a lot for your help guys this stuff is currently implemented in a very ad hoc manner which has hampered my ability to extend it, you've given me some great ideas for how to systematize "effects"

#

every time i arrive at a new problem to solve or feature to implement, i think implementing that will be relatively easy but... then i sit down and think about it and it really requires a lot of time

heady iris
#

an effect system is like

#

two steps away from a programming language

#

The closer you get to implementing an entire programming language, the harder it becomes

tardy crypt
#

funny

heady iris
#

At some point you just cut your losses and implement some things in C#.

tardy crypt
#

Your "Effect" class just has a text field and a runtime compiler. No interfaces, no hierarchy. Just create new SOs for each effect and give it a name and a string parameter, into which you type your effect code.

#

I actually briefly considered doing that until I realized that debugging this would probably majorly suck.

#

Though I feel like large devs actually do this with scripting (e.g., LUA) and whatnot.

latent latch
#

Dota does a lor of lua

#

For its ability systems

#

I considered it

tardy crypt
#

I mean it's a nice way to decouple gameplay design logic from core gameplay logic.

#

but the infrastructure required for a small project is too high of a cost.

#

basically, even with the extremely frictionless nature of the C#/VS environment, this project still takes tons of time, so downgrading to whatever would be required for scripting would result in a significant slowdown.

surreal cloak
#

anyone have any idea of what is the best way to pull off something like this when the camera is looking at the body/gun. I was thinking of having a square collider coming out of the head that shows where the player is looking at and checking if its looking at a gun collier. 10 mins into itegrating it i realised how uterly retar*** my method was and i currently dont have any other ideas

#

and follow up question. Is it possible to have two "OnTriggerStay" methods for two colliders in the same class

spring creek
#

One method with the same name and signature per class

#

You can validate the collider type INSIDE the same OnTriggerStay, and simply do different things depending on the collider

heady iris
#

OnTrigger* methods don't tell you which of your colliders caused the message to be sent.

#

If you want multiple distinct colliders, you need to put them on different objects

spring creek
#

You can check the SHAPE if they are different.

#

Or check some parameter of the collider (like if one has a high radius and the other is small)
It is unweildy though

#

I agree that separate objects is generally the best way to go though
That's what I do

tropic cave
#

hello, any suggestion for a lite version of unity ? I dont want to really make a full game but to test some code on an objects with physics properties and such stuff

spring creek
#

Other than that, not really

tropic cave
hidden compass
#

interesting

pale marsh
#

Are these errors really that important, because the code works fine?

heady iris
#

This is a problem with the inspector.

#

I'll sometimes see then when I undo or destroy things.

pale marsh
#

is there a way to bypass it?

heady iris
#

it's usually solved by restarting the editor

#

assuming it's spamming the error constantly

pale marsh
pale marsh
naive swallow
#

In general, if you look at the stack trace and see no actual line numbers, it's the editor being fucky and a quick restart will at least supress it for a while

pale marsh
#

yeah I just restarted it and now its not showing anymore, so that will do it for now

#

thanks yall

brittle haven
#

How can I get the sizes of a sprite in a script?

ocean hollow
brittle haven
swift falcon
#

can someone please help me i want to make an object appear in unity in a 2d game when i hold down s and when i release it it disappears again

thats my script (it does not work)

using UnityEngine;

public class ShowOnKeyPress : MonoBehaviour
{

public GameObject objectToShow;


void Update()
{

    if (Input.GetKey(KeyCode.S))
    {

        if (objectToShow != null && !objectToShow.activeSelf)
            objectToShow.SetActive(true);
    }
    else
    {

        if (objectToShow != null && objectToShow.activeSelf)
            objectToShow.SetActive(false);
    }
}

}

brittle haven
modern creek
# swift falcon can someone please help me i want to make an object appear in unity in a 2d game...

If this is the only thing controlling whether or not the object is active, just check if the object isn't null in Awake() instead of in Update(). ie - your code could be a lot simpler if it looked like:

public class ShowOnKeyPress : MonoBehaviour
{
  public GameObject objectToShow;
  private void Awake()
  {
    if (objectToShow == null)
    {
      // log a warning here or whatever
    }
  }
  private void Update()
  {
      objectToShow.setActive(Input.GetKey(KeyCode.S));
  }
}
#

also activeSelf means "is this exact gameobject active" which is different than activeInHierarchy (since a parent could be inactive)

swift falcon
#

i found the problem i apply the script that i want to appear with s and then the script disable it self when i start the game

#

but thx for our help

#

i had another problem how can i cut the yellow circle at the blue line i want to make a car headlight

modern creek
#

with a Mask or SpriteMask component

ocean hollow
brittle haven
#

I throw this sprite into sprite renderer

swift falcon
ocean hollow
#

In a script, you can modify the scale of a sprite by using gameObj.scale

brittle haven
ocean hollow
#

So you are talking about the texture?

#

Nothing you say is adding up

brittle haven
#

it could be

ocean hollow
#

I need to know what you're talking about before I can help you

#

You should do some research on unity lingo

brittle haven
#

what do I need to write to get the sizes of this sprite?

ocean hollow
heady iris
#

Are you asking what the apparent size (in world units) of a Sprite would be if you put it into a SpriteRenderer that had a default scale?

#

Or do you want the actual resolution of the image?

leaden ice
brittle haven
#

width and height

#

or vector2

tardy crypt
#

width and height in world coords?

#

everybody is saying there's a bunch of different notions of size for a sprite because there's the underlying image which has a resolution in pixels and then the sprite also has a world size which is related but also different than the resolution of the image

heady iris
heady iris
#

Do you care how many pixels are in the sprite?

#

Or do you care how big it will look in a SpriteRenderer?

brittle haven
knotty sun
golden garnet
#

Any ideas for this?

rigid island
#

the code is empty

ocean hollow
mellow grail
#

I'm trying to make a game that uses a hexabody like character controller similar to the one so see in boneworks, i cant seem to get the hands how i want them though, they are always to springy and since part of the game will have you use your hands to walk (unoriginal trust me i know) this will make it really difficult to move around, maybe ill add this springy hand feature as a weapon of some kind but for now it would be nice if they were more rigid.

#

ive tried maxxing out the spring values but it didint seem to help to much

#

nvm

#

turns out the sping being high was the issue

mellow grail
#

what

golden garnet
weary glade
#

Hey, can someone help me, im working with the a* Pathfinding assets, and for some reason the seeker just always seems to pick a way through obstacles, any ideas?

weary glade
plucky inlet
#

Wait

#

Research

#

Test

rigid island
#

yup. its also difficult to help on a specific asset especially if you don't explain any of the setup.

void turtle
#

loving this debugger deadlock

sleek heath
void turtle
rigid island
sleek heath
rigid island
compact spire
#

Is using addressable assets really worth it? It seems like you can't mix "normal" assets with addressable assets, so that means you have to create a wrapper for any assets from the asset store right?

spring creek
#

Addressables just create an address for assets so you can load them from that

plucky inlet
compact spire
#

I see, I didn't realize there was a channel for addressables

heady iris
#

one in Addressable-land and one that isn't

compact spire
#

@heady iris That seems problematic

heady iris
#

I discovered this while I was trying to use Addressables to load all assets of a certain kind into a dictionary

#

(so that i could avoid manually referencing them or stuffing them into one giant Resources folder)

#

The really confusing part is that it works fine in the editor

#

It just fall apart in the build

spring creek
compact spire
#

@heady iris isn't that what labels are for?

heady iris
compact spire
#

@heady iris If you put a bunch of assets under the same label you can load all addressable assets that match the label.

heady iris
#

Oh, you mean addressable labels. That’s what I was doing :p

#

But I needed references to the same objects that everyone else had

compact spire
#

ahh

heady iris
#

The addressable-loaded objects were unrelated to the directly-referenced objects

compact spire
#

I'm still trying to wrap my head around the whole thing, but I understand bits of it

#

or at least I think I do

visual flare
#

CanEditMultipleObject is no more, what's the new flag for that?

leaden ice
#

The closing one belongs before the comma

quartz folio
#

Probably worth making less assumptions

visual flare
#

i didn't know you could pile up attributes like this

leaden ice
#

You could also put each in their own [] brackets

#

Up to you

low mirage
#

!code

tawny elkBOT
low mirage
#

Hello people, I am new here so, hi.
I am having problems with this while loop that causes the entire unity engine to crash:

private void getNewPosHanger()
{
    float posY = 4.5f;
    bool isLooping = true; 

    while(isLooping)
    {
        float positionEnemySetX = Random.Range(minRangeEnemyHanger, maxRangeEnemyHanger);

        if (!isRayCastPosFull(new Vector2(positionEnemySetX, posY)))
        {
            posNextHangerEnemy = new Vector2(positionEnemySetX, posY);
            break;
        }
    }
}

This function allows me to get a new position for the next enemy on screen, but it checks if that new position is already taken by another foe (that's what the isRayCastPosFull does).
I call this function when the enemy is created an in the start of the gameobject so the next enemy already has their position.

lean sail
#

If that break is never reached itll never exit

low mirage
#

any other ideas on how to implement that behaviour?

hallow portal
low mirage
#

2d

lean sail
hallow portal
#

if 2d that this private void getNewPosHanger()
{
float posY = 4.5f;
bool isLooping = true;

while(isLooping)
{
    float positionEnemySetX = Random.Range(minRangeEnemyHanger, maxRangeEnemyHanger);

    if (!isRayCastPosFull(new Vector2(positionEnemySetX, posY)))
    {
        posNextHangerEnemy = new Vector2(positionEnemySetX, posY);
        break;
    }
}

}

#

something like this

simple egret
#

And add a safety that breaks out of the loop if no valid positions have been found for like 1000 iterations!

low mirage
#

or maybe with a for loop

lean sail
#

Count how many times its looped or use a for loop

simple egret
#

You use a variable declared outside the loop, or a for loop. Either works

low mirage
#

let me try that one

lean sail
#

You should show what that method is doing also. It could be that you're simply returning true all the time so the break never happens

#

An also, test the method alone so you know it works before using it elsewhere

simple egret
#

Yeah if it always returns true, either the ray is too long, hits something unexpected, or hits the same position every time (if your random min/max variables are identical)

low mirage
#

I don't think it's the problem but you never know, it basically casts a circle in the given position

#
private bool isRayCastPosFull(Vector2 location)
{
    RaycastHit2D ray = Physics2D.CircleCast(location, 1f, new Vector2(1, 0), layerEnemy);
    if (ray.collider == null)
    {
        return false;
    }
    else
    {
        return true;
    }
}
simple egret
#

layerEnemy is a layer mask, correct? Not a single layer index

lean sail
simple egret
#

(also that big if statement can be simplified down to a single return ray.collider != null;)

lean sail
#

Another thing I just noticed too is that you are doing a random selection for the X value until one is found. This means theres a very likely chance you are checking the same position over and over.
If you truly need a random place, i would increment x by some amount and check along the entire area. Then return a random index of the areas that were valid

#

This would save time in the case where only like 1/50 spots were valid

low mirage
#

new info, the check is working just fine, but I will implement this idea, because right now it's looping for a long time a cannot find any avaliable position, even though there are some blank spaces

agile carbon
#

guys https://youtu.be/CdPYlj5uZeI?t=784 this video mentions splitting the vector into two components. how does it do that? isnt dot product combining not taking apart?

A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy

~ More from Toyful Games ~

▶ Play video
quartz folio
#

Probably worth noting where in the video you're talking about

agile carbon
#

if u press play it starts where im talking abt

quartz folio
#

The dot product is a scalar portion of vector projection

agile carbon
quartz folio
#

The result of those two dot products is the vector split up into two in the way they're talking about

agile carbon
quartz folio
#

yes, and he shows two dot products

agile carbon
quartz folio
#

The (length of the) white arrows on those lines, yes

agile carbon
quartz folio
#

the direction the tyre faces and a perpendicular direction to that

quartz folio
#

presumably you have the rotation of the wheel, so you can easily get those vectors from that. If you have a transform you can just use transform.forward and transform.right if it's not being rotated around like the wheel visuals

agile carbon
#

the angle at which the wheel is turned

quartz folio
heady iris
#

neat video!

agile carbon
quartz folio
#

I don't know what you mean, the forward and right directions should be normalized when used in the dot product

#

and the result of the dot products with the velocity are the components they're talking about

agile carbon
agile carbon
gentle glen
#

Yo can I ask for help in scripting here?

quartz folio
agile carbon
quartz folio
#

Yes

agile carbon
#

tysm

gentle glen
#

Yo

spring creek
gentle glen
#

I tried using WorldToScreenPoint on a GO but it always goes to the bottom left

#

I use a list and an index for the Transform

spring creek
tawny elkBOT
gentle glen
#
if(LockedOn)
        {
            lockOnGraphic.SetActive(true);
        }
        else
        {
            lockOnGraphic.SetActive(false);
        }
        enemyPos = GetComponent<TargetList>().Targets[tgtI].GetComponent<EnemyPosition>().enemyPosition;
        lockOnGraphic.transform.position = camera.WorldToScreenPoint(enemyPos.position);
#
//This is the defenitions
public Transform enemyPos;
public bool LockedOn;
public GameObject lockOnGraphic;
#

@spring creek

#

enemyPosition gets the transform of the enemy GO

spring creek
hexed pecan
#

You are using a screen position as a world position

gentle glen
#

oh wait

#

nvm

gentle glen
hexed pecan
#

There are ways to set a recttransform's screen space position (assuming that lockGraphic has a recttransform).
I dont remember how though

gentle glen
#

yeah lockOnGraphic is a parent of an image and one slider

hexed pecan
gentle glen
#

what i've also noticed is that this code worked perfectly before

#

and when i used a list getting automatic values it got bugs like that

#
//List class
public class TargetList : MonoBehaviour
{
    public List<GameObject> Targets = new List<GameObject>();
    public int targets;
    
    // Start is called before the first frame update
    void Start()
    {
        if(GameObject.FindGameObjectsWithTag("GiodEBody") != null)
        {
            Targets.AddRange(GameObject.FindGameObjectsWithTag("GiodEBody"));
        }
        if(GameObject.FindGameObjectsWithTag("EnemyTurret") != null)
        {
            Targets.AddRange(GameObject.FindGameObjectsWithTag("EnemyTurret"));
        }
        
    }

    // Update is called once per frame
    void Update()
    {
        Targets.RemoveAll(s => s == null);
        targets = Targets.Count - 1;
        if(Targets.Count == 0)
        {
            targets = 0;
        }
    }
}
modern creek
#

if Targets.Count is 0, targets will be -1.

agile carbon
#

If I have a vector that is: (-0.6401844024658203, -0, -0.7682212591171265) would the perpendicular vector be (0.7682212591171265, -0, -0.6401844024658203)?

agile carbon
#

for my dot product?

quartz folio
#

the velocity is not normalized, the directions should be

agile carbon
#

cause isnt velocity direction and magnitude like a vector

quartz folio
#

I don't know what you mean, the velocity is a vector that has a magnitude that is the speed

agile carbon
quartz folio
#

Yes

agile carbon
#

or wait.

quartz folio
#

No, it returns a magnitude

agile carbon
#

oh a magnitude of the red?

agile carbon
#

jeez vectors are interesting

#

will i learn this in AP physics? 😭

hollow crane
#

I think they do a little bit w vectors in AP

#

it’s mainly calc 3 tho