#archived-code-general

1 messages · Page 75 of 1

tired drift
#
internal class SurvivorData
    {
        [JsonProperty] public List<Survivor> survivors = new List<Survivor>();
        [HideInInspector, JsonProperty] public List<Survivor> FreeSurvivors = new List<Survivor>();
    }```
#

example

#

i send this to the GameData dictionary like this

SurvivorData data = new SurvivorData();

    public List<Survivor> survivors => data.survivors;
    public List<Survivor> FreeSurvivors => data.FreeSurvivors;

 void WriteToSave() => DataManager.SaveData(DataType.survivor, data);```
#

it will always save multiple objects tho? i guess that's what you've meant

knotty sun
#

but not multiple objects of multiple types

cold parrot
tired drift
#

pretty much needs to work like one in my head

cold parrot
tired drift
tired drift
#

that's why it's generic

cold parrot
tired drift
#

but the dictionary collects those and saves them existential so i guess it does handle multiple ones?

#

idk how i could make it better tbh

knotty sun
tired drift
#

1 gameData has a dictionary with 1 key that equals 1 object

#

another key can be a totally different object

cold parrot
tired drift
#

isn't that handling multiple objects screamcat

tired drift
knotty sun
tired drift
#

plus JSON is easier like screamcat

tired drift
#

i mean in my head it can handle multiple types

knotty sun
tired drift
#

but aren't you making multiple Save files and then combining them in a single one?

knotty sun
#

no

tired drift
#

hm then?

knotty sun
#

one save file, containing anything you want

tired drift
#

1 Save file is handling multi-type, if i'm not wrong, SurvivorData and InventoryData aren't the same right?

knotty sun
#

no it's not, you have one call to save, which means you have one class defining everything you want to save

tired drift
#

hm

knotty sun
#

your code cannot call Save twice on the same file

tired drift
#

how so? sorry i'm kinda slow cuz i didn't sleep much today

knotty sun
#

you have no append, no indexing, no file descriptors

tired drift
#

wdym indexing?

#

i'm utterly confused

knotty sun
#

I mean, pulling individual objects out of the save file

tired drift
#

you can tho

#

wait let me show you how the save looks

#
{
  "_saveData": {
    "0": {
      "$type": "Core.Data.SurvivorData, Assembly-CSharp",
      "survivors": [
        {
          "movespeed": 20.0,
          "isBusy": false,
          "isInShelter": false,
          "name": "Donald Hall"
        },
        {
          "movespeed": 20.0,
          "isBusy": false,
          "isInShelter": false,
          "name": "Kathleen Lewis"
        },
        {
          "movespeed": 20.0,
          "isBusy": false,
          "isInShelter": false,
          "name": "Thomas Jackson"
        }
      ],
      "FreeSurvivors": []
    }
  }
}```
#

it will take the 0 out which is all the survivors and free survivors out of the list

#

1 would contain inventory

#

2 shelter / city etc etc

knotty sun
#

no, you have to load all of them in order to be able to access any one of them. If I want, only e,g, survivors number 1 then you cannot do it

tired drift
#

ah it's not the point either

#

but i can create a method for that

#

can i not?

knotty sun
#

no you cannot, that is not the way Json works

#

it is all or nothing

tired drift
#

i mean, SurvivorData is a list, and i really won't care much with the individual aspect of 1 survivor

steady moat
#

You can separate in multiple files.

tired drift
#

at least on the game design it doesn't matter much, and from the top of my head i don't see where being able to handle 1 survivor or 1 piece of info can be necessary. (does it make sense?)

#

i really just want to pick up a list of x things and read and load them. But i'm always open to other POVs

knotty sun
tired drift
#

but do you think i should go for something where it can handle 1 object inside the list at the time?

#

It's like i've said, i don't really need to access that type of info during loading, since it's not really important hence the why i've made it this particular way

#

or saving 1 specific survivor

knotty sun
tired drift
#

i mean i only considered of doing loads during the start of the game / whenever a save is loaded

tired drift
#

where i can serialize those objects inside the save?

knotty sun
#

You need to add a structure to your save file, on top of your Json, that way you can access parts of the file without having to pay the overhead of accessing all of it

#

think about the way that FAT tables work on disks

tired drift
#

screamcat trauma

#

but what type of structure would that be i mean, like inside the json or outside, where the json would be inserted?

knotty sun
tired drift
heady iris
#

Serialization is always traumatic

knotty sun
tired drift
#

now you left me curious screamcat

knotty sun
#

@heady iris is right, Serialization, done correctly, is not for the uniniated

heady iris
#

one thing that can help is separating "authoring data" from "runtime data"

#

for example

#

in my soulslike I'm working on, your inventory is full of InventoryItems

#

these contain instructions for how to create an actual weapon you hit things with

tired drift
#

it's like i've said, i haven't really developed many S&L systems, and the ones i've made were pretty simple compared to this one

heady iris
#

so I'm not going to have to serialize the actual weapons

#

just the blueprints

tired drift
#

I mean all the data i'm saving is pretty much runtime there isn't anything really authoring, at least for now. Maybe when i get to the shelter / city it may contain some type of data where that separation is needed, but ty for the tip ^^

knotty sun
tired drift
#

just peeped quickly, but yeah some parts will change during runtime but most of it is authoring

knotty sun
tired drift
#

so you're saying if the stuff i save from the SO changes during runtime it won't save correctly? existential

knotty sun
#

correct

tired drift
#

more changes Sad_chip_Blanket

#

f

#

so the SO can only have the authoring parts welp

knotty sun
#

yes

tired drift
#

gonna be a pain but not for me kek

#

hmm i mean we were using SOs with some mutable variables, but i didn't even consider the save and load question at the time tbh

knotty sun
#

forget mutable variables in SO at runtime outside of the Editor, Ain't gonna work

tired drift
#

but now you left me thinking if my S&L system is too bad in a overall, even if i don't want to access a list, but instead load everything at once every load cuz i mean that's how we were thinking of doing.

tired drift
knotty sun
tired drift
knotty sun
#

Biggest problem is different behaviour in Editor and in Build. Bad Unity

tired drift
#

anyway yukkuri_kouhai guess i'll work on the changes once again i appreciate for the golden nuggets you've gave me

calm saddle
#

!ide

tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

knotty sun
tired drift
#

blush_cat oke will do, i appreciate it

stone rock
#

Hello, when using assembly references in Unity, does everything have to be in a folder with an assembly reference or can i have a script in the default C-Sharp assembly? how can i make my assembly reference include the C-Sharp default assembly?

leaden ice
#

Make a game assembly and have the other assembly reference it.

stone rock
#

so you can't have a reference to the default C-Sharp assembly then

leaden ice
#

No

stone rock
#

i see i'll add an assembly at the root of my scripts folders then

fluid lily
#

Anyone else having an issue of scripts inside Editor folders being included on build? I thought any folder called Editor wouldn't be included on build.

leaden ice
fluid lily
#

C:...\Assets\Modules\Levels\Unity\Level1\Editor_Extensions\PropertyInspectors\Editor\HideInNormalInspectorDrawer.cs

#

That file I had to put #if UNITY_EDITOR on

simple egret
#

Assembly definitions override Editor folders, if I remember correctly

simple egret
#

So if you have one that encloses that folder

fluid lily
#
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;

[CustomPropertyDrawer(typeof(HideInNormalInspectorAttribute))]
class HideInNormalInspectorDrawer : DecoratorDrawer {
    public override float GetHeight() {
        return 0f;
    }

    public override void OnGUI(Rect position) {
        // do nothing to prevent the field and any custom property drawers from being displayed in the inspector
    }
}
#endif
leaden ice
#

Yeah only thing I can think of is you have an assembly definition

fluid lily
#

That is annoying

leaden ice
#

You can just set the assembly to not be included in the build

fluid lily
#

I can see it being useful, but annoying that it isn't clear that happens

leaden ice
#

If you are mixing editor and non editor stuff in one assembly you will need to split it up though

fluid lily
#

I mean, or just compiler directive it

leaden ice
#

That's wasteful though...

#

Why include files in your build that have no business being there

#

A few clicks in the editor > writing a bunch of preprocessor directives in many files

fluid lily
#

If I have a larger number of files I would agree, but it is just that one currently.

#

Though also I have some functionality that can use Undo in editor(or just normal in build) so having a version of each makes sense, and then already have functionality specific to different platforms anyways.

jovial turret
#

hi

plush sparrow
#

public class spawnRes : MonoBehaviourPunCallbacks
{
  if (PhotonNetwork.LocalPlayer.ActorNumber == 1)
        {
            GameObject sco = PhotonNetwork.Instantiate(Score.name,new Vector3(0f,0f,0f),Quaternion.identity);
            GameObject go = PhotonNetwork.Instantiate(Dice.name,new Vector3(0f,650f,0f),Quaternion.identity);
            sco.transform.SetParent(Canvas.transform, false);
            go.transform.SetParent(Canvas.transform, false);
        }
        else
        {
            GameObject sco = PhotonNetwork.Instantiate(Score.name,new Vector3(100f,0f,0f),Quaternion.identity);
            GameObject go = PhotonNetwork.Instantiate(Dice.name,new Vector3(0f,650f,0f),Quaternion.identity);
            sco.transform.SetParent(Canvas.transform, false);
            go.transform.SetParent(Canvas.transform, false);
        }
        
            
    }```
#

when two players are joining. they can only see their own instantiated objects

#

and cant see each others

#

what is the problem?

#

i have added a photon view component along with a photon transform view component to the prefabs of the instantiated objects

simple egret
plush sparrow
#

oh ok

simple egret
# plush sparrow oh ok

But check if your Instantiate method here can take a parent Transform directly. It's never good to instantiate an object in world space and then parent it to UI. It messes with the RectTransform

#

It might not solve your issue, but it's a step forward to better object management

plush sparrow
#

ok thanks

#

here can take a parent Transform directly

#

what do you mean exactly

simple egret
#

Regular Instantiate has a version where you can pass a Transform directly to it, aside the position and rotation

#
Instantiate(prefab, pos, rot, parent)
#

So check if your networking one can do that too

ocean river
#

hey um,
ive got a question.
i have two gameobjects, and one of them HAS to be initialized before the other.
i mean the gameobjects themself tho.

leaden ice
#

Make a script that spawns one then the other

#

Or have the first one spawn the second one

#

Also you didn't actually ask a question 😂

primal marlin
#

hey guys i have a projectile which spawns an explosion particle system after it enters a collision. the issue is this explosion particle stays at the same place and doesnt happpen where the projectile has collided

#

here is the projectile code

#

here is the projectile hierarchy

leaden ice
#

Also you don't need the .gameObject there

ocean river
#

are awake and start called when a scene is loaded as additive?

ocean river
#

only when i load the scene directly.

potent sleet
ocean river
#

never mind, it was filled with audio listener msgs so i didnt see...

simple egret
#

We don't help with modding in this server

#

I don't make the rules, sorry

severe saddle
#

I tried this script to download a pdf file from the given url. It works on PC but not on android. Pls help!

buoyant shuttle
#

Can someone help me out? :(. I'm trying to get the forward bounds of my collider in world space. In particular I need the center bottom forward. I marked with a red dot the position I'm aiming to get. I can't quite figure it out since bounds has size and center.. But doesn't translate from local to world etc.

heady iris
#

find the point in local space, then transform it to world space

leaden ice
heady iris
#

oh hey, I never knew that you could do a raycast on a single collider!

#

neat

leaden ice
#

Yep

#

Also wrote this on my phone so it's a little rough

heady iris
#

but yeah, I'd just do transform.TransformPoint(collider.center + Vector3.Forward * collider.bounds.z)

#

i forget if bounds is half-width or full-width

#

if it's full-width, divide by 2

leaden ice
#

The bounds aren't quite the actual collider shape though

#

You can also just make a child object at the point you want

#

And use that position

wide star
#

someone help me fix this bug, because I'm trying to make the button turn on application from game files but something didn't work, because it can see the file but won't turn it on something

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

public class UEChanger : MonoBehaviour
{
    string m_Path;

    public void ChangerToUnrealEngine()
    {
        m_Path = Application.dataPath;  Process.Start("/Ognaria_Data/Resources/UnrealEngineSource/WindowsNoEditor/Ognaria.exe");
    }
}
cerulean oak
#

how does adding/removing/renaming fields work with BinaryFormatter? Does it stop working? do they get deserialized as a default value?

leaden ice
cerulean oak
#

why not?

#

what about xml?

#

or json?

#

but those dont have references right?

#

how do i handle versioning with serialization? What should I use to serialize/deserialize?

swift falcon
#

does the using directive import the entire library ?

#

Im asking because what if i only want one class from the library do i have to drag in everything else as well?

lucid valley
heady iris
swift falcon
#

Oh because it may be refernecing other classes in the lib?

lucid valley
#

yeah, you probably can't just take the file on its own

lucid valley
#

having the whole library would increase build size, but wouldn't reduce performance (unless you are really ram limited maybe)

cerulean oak
#

The compiler should be able to optimice the import of the library

lucid valley
cerulean oak
#

And unless you are running whatever you are making in a potato and the library is huge, it shouldn't be a concern

#

The java compiler optimizes it, I don't see why the .net one wouldnt

lucid valley
#

well yeah code size isnt generally an issue for Unity games

#

Ordinarily, the build process includes the entire assembly file, no matter how much or how little of the code in an assembly your Project uses.

#

No idea if that is the mono/.net default or if Unity has changed it

heady iris
#

this is for IL2CPP

lucid valley
heady iris
#

oh, d'oh, you're right

cerulean oak
#

That's the answer to his question, but honestly, what he should hear is very likely "don't worry, it won't matter"

heady iris
#

ya

nova roost
#

Is there an easy way to check if an object is a 2D Canvas object or a 3D one?
I guess I could check if the transform component is a rect transform or a Transfrom, right?

heady iris
#

yeah

#

that's what I'd do

#

transform is RectTransform

nova roost
#

didnt know its that easy

low horizon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ResourcesManager : MonoBehaviour
{
    public static ResourcesManager current;
    private void Awake()
    {
        current = this;
    }


    public GameObject exampleObject;

    private void Start()
    {
        exampleObject = Resources.Load<GameObject>("exampleObject");
    }
}
#

is this an acceptable way for using resources folder

#

basically a singleton that loads them all

#

and other scripts get prefabs etc from that

#

what is the generally used method for this?

leaden ice
low horizon
#

for each scene

#

oh i can use prefabs

#

thanks

#

can i do static GameObject and drag them in editor

leaden ice
#

so I'm not sure what you would have been doing before

low horizon
#

i was

#

lost

leaden ice
#

static is right out for the inspector

low horizon
#

thanks

#

what is resources.load used for then

leaden ice
#

dynamically loading assets by name

low horizon
#

oh

leaden ice
#

honestly in serious projects, Resources.Load is not used at all, Addressables are.

low horizon
#

i don't know what is addressables

#

let me check them

#

thanks

leaden ice
#

Resources.Load can be useful for lazily loaded singletons and self-initializing singletons / ScriptableObjects

worldly hull
#

and then by using the API, u get to spawn stuffs without assigning them on inspector

leaden ice
#

Addressables lets you reference assets without immediately loading them into memory peepoWink

low horizon
#

it looks like the exact thing i was looking for

worldly hull
#

imagine u have 10000+ assets in ur folder, its extremely hard to find them everytime right? if u can register the stuff u want onto the addressables. You will have a simpler menu to access them

#

normally i wont use addressables, but my team does, even tho they use it very differently unlike the normal way

worldly hull
#

i think one of the most important reason of ppl using addressables is the decentralization

low horizon
#

when the project gets bigger referencing stuff becomes hell

worldly hull
#

just pack ur folder well bruh

#

but i guess addressables is fine if u have tons of stuff

low horizon
#

its like

#

i am using scriptable objects

#

that summon modular components

worldly hull
#

and i still need someone to explain more bout it to me tho
i joined a team project for like 6months, and the image that addressables left me is just bad

low horizon
#

it looks like

worldly hull
#

maybe its because how my team use it differently

low horizon
#

it lets u load stuff

#

with code

low horizon
#

rather than inspector

primal marlin
#

how would i go aboout doing that?

low horizon
#

thats what i am looking for

#

so i'll try adressables

leaden ice
worldly hull
primal marlin
#

im getting an error on this line:

#

Transform position = transform.position;

#

'Cannot implicitly convert type 'UnityEngine.Vector3' to UnityEngine.Transform'

potent sleet
primal marlin
#

Vector3 position = transform.position;

#

also gives error

potent sleet
primal marlin
#

Argument 2: cannot convert from 'UnityEngine.Vector3' to 'UnityEngine.Transform'

primal marlin
#

yes

#

its a different error

#

OH DIFFERENT LINE

#

sorry

#

the line is this one

#

GameObject ps = Instantiate(explosionParticleSystem.gameObject, position);

#

can i not use vector3s for instantiate argument 2?

potent sleet
#

or else rn it's a Parent parameter which is only Transform

potent sleet
primal marlin
#

thank u!

potent sleet
primal marlin
#

thx

#

i did but i thought rotation was not necessary

potent sleet
heady iris
#

there are only two overloads

#

Transform
Transform, Vector3, Quaternion

#

er

#

i am very wrong on that number!

#

there are 10, lol

worldly hull
#

GameObject , Transform

heady iris
#

oh yeah

#

i forgot the gameobject

#

lol

#

but yeah, there's no overload that only takes a position

worldly hull
#
instantiate(GameObject)```
i think its same as 
```cs
instantiate(GameObject,Vector3.zero,quat.identity)```
#

which spawn stuffs on origin

worldly hull
#

you can create one tho, even its not really necessary

#
public void Instantiate_PosOnly(GameObject obj, Vector3 pos){
      Instantiate(obj,pos,quat.identity);
}```

when u call this function, it will act as ```cs
instantiate(GameObject,Position)```
knotty sun
#

well, if you dont mind compile errors instead of running code

heady iris
#

you could write an extension method :p

#

i forget if it gets mad if you make an extension method with the same name as an existing one

knotty sun
#

no, you can overload extensions

heady iris
#

nice

worldly hull
#

oh wait

#

u can

#

that thing is transform

knotty sun
#

you're in a different namespace anyway

worldly hull
#
Instantiate(GameObject,Transform)
Instantiate(GameObject,Vector3)```
#

yes u can

civic folio
#

What's the difference between vector3 and float3?

cold parrot
knotty sun
heady iris
#

they're basically the same thing under the hood

#

three floats glued together

latent latch
heady iris
#

trig time! trig time!

#

well, sort of

#

A rotation of one radian around a unit circle will move you by exactly one unit

#

because the circle's radius is 1

#

diameter is 2

#

circumference is 2pi

#

and it's 2pi radians to make a full turn!

#

so, dividing the rotation speed by the radius will do the trick

latent latch
#

I fell asleep in trig. Would been more exciting if I found it useful at the time.

heady iris
#

well, you're in for a treat in game dev :p

cerulean oak
#

I added the newtonsoft package, but rider isnt detecting any newtonsoft classes

#

any ideas about what i should look for?

heady iris
#

you might need to regenerate the project files in the External Tools menu

knotty sun
cerulean oak
#

with the package manager

knotty sun
#

can you see it in your packages folder in the project?

cerulean oak
#

yes

knotty sun
#

you have added the correct using statments?

cerulean oak
#

ok regenerating the project files worked

cerulean oak
#

but its working now

#

thanks!

rain tide
latent latch
heady iris
#

let's see

heady iris
#

with a known radius

latent latch
#

Yeah, that's probably the idea

heady iris
#

Dividing by the radius will make it so that rotating at one radian per second makes you move at one meter per second

#

er

#

that was not the correct way to say that!

#

lol

rain tide
#

Hello?

heady iris
#

if you rotate by 1/r radians per second, you will move at 1 meter per second

#

there we go

heady iris
heady iris
rain tide
#

I was just seeing if you would notice me, I'll wait, thanks!

latent latch
#

So, x in this case would be speed * Time.deltaTime or is there more to this? At the moment it's much, much slower with that than a linear projectile

heady iris
#

yes, you'd multiply deltaTime in afterwards

rain tide
latent latch
#

Angular to linear velocity I would assume

rain tide
heady iris
#

if you rotate with a radius of 1 at 1 radian per second, the object should appear to be moving at 1 meter per second

#

is it appearing much slower than that?

latent latch
#
          transform.RotateAround(sourceSpawnPosition, transform.up, ability.StatDict[AbilityStatType.AbilitySpeed]/ability.StorableSO.DistanceOffset * Time.deltaTime);```
#

does travel much slower than my normal fireball of ability.StatDict[AbilityStatType.AbilitySpeed] * Time.deltaTime * objectDirection;

heady iris
#

is objectDirection normalized?

latent latch
#

Ah, actually I don't normalize this one

heady iris
#

that'll do it!

latent latch
#

There's probably something I'm doing wrong beyond that, but I'll revise on what ya said

#

tyty

rain tide
#

Alright, good luck!

heady iris
#

so gideon, your character spins rapidly when you try to back up?

rain tide
#

Yeah.

#

I've been trying to fix it for the past 2-3 hours.

heady iris
#

i noticed that both the horizontal and vertical movement affect the y-axis rotation

rain tide
#

oh.

#

So what do I do to help with it?

heady iris
#

well, I don't really know what your intent is here

#

can you explain what this is doing?

rain tide
#

So, it's a movement script that is supposed to work with Keyboard and mouse, and controller with animations, I would of used the Input system asset, but I found it easier to do this.

heady iris
#

so it tries to rotate you to face the direction you're moving in

#

although you only have the vertical component on the direction vector

rain tide
#

Yeah, I use the Horizontal just for turning.

heady iris
#

but you're already turning?

#

i don't understand

rain tide
heady iris
#

ah, I see

#

oh

#

one big thing...

#

you add the rotation of the camera to the desired rotation

#

so if the character rotates a bit, the camera gets rotated too, right

#

and now it wants to rotate even further

rain tide
#

Is that why?

#

So do I get rid of the camera part?

heady iris
#

If the camera is always trying to stay behind the character, then it will be impossible to walk towards the camera

#

and you'll just spin violently

#

see how it behaves with a fixed camera

rain tide
#

So, what do I do?

rain tide
heady iris
#

ideally, the camera shouldn't rotate when the player rotates

#

i'd suggest using Cinemachine for this

#

the Free Look Camera is a good fit

rain tide
#

I don't wanna use the FreeLook camera.

#

I need a fixed camera.

heady iris
#

so you don't want the camera to ever rotate?

#

or do you want it to always be exactly behind the player

rain tide
#

I want it to rotate with the player.

#

Ideally.

heady iris
#

if so, then you'll need to make it so that the player doesn't rotate when moving backwards

#

float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + Camera.main.transform.eulerAngles.y; you can probably just get rid of this entirely

rain tide
#

How do I just make it walk backwards?

heady iris
#

you don't have a horizontal component in there -- you do that rotation separately at the end

#

so all this can possibly do is try to rotate the character 180 degrees around

rain tide
#

What do I do here: ```cs

Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward * Speed * Time.deltaTime;

heady iris
#

I guess you can still compute the target angle

#

just don't use it to rotate the player

rain tide
#

Ok.

#

One sec.

#

It doesn't spin, but when I go backwards, it moves forward.

#

Wait, let me fix something.

slim flower
#

I have a question

#

I have this player script i made which is a mix of my stuff + changed carlson movement bc im lazy and other crap

#

but now i have this problem where it automaticly adds a character controller to the player object

#

and idk why

heady iris
#

it probably has a [RequiresComponent(typeof(CharacterController))] at the top

slim flower
#

i use a rigidbody movement so you could undrstand why this is a big problem

heady iris
#

or it adds it somewhere in the script

#

you can just ctrl-f for CharacterController

slim flower
#

nothing shows

slim flower
slim flower
#

i can make a pastebin of the script to show

slim flower
leaden ice
#

when is the CC being added?

slim flower
leaden ice
#

and how does the player get into the scene? Is it there from the start? Is it spawned?

slim flower
leaden ice
slim flower
#

even when i rememove it

#

but

#

when i disable it it stays disabled

slim flower
leaden ice
#

Ok so what components are on the prefab?

#

Can you show the inspector?

slim flower
#

yes

heady iris
#

well it's right there

#

albeit disabled

slim flower
#

yes

#

but i really want it gone

#

not just disabled

leaden ice
#

Check all of those scripts

slim flower
#

when i remeove the playercontroller script it doesnt auto add the CC

#

its only with the PlayerController script

leaden ice
#

I'd guess it might have something to do with mirror

#

something about how prefabs are registered with it perhaps

#

Unrelated but:
float mouseX = Input.GetAxis("Mouse X") * Time.fixedDeltaTime * sens * 50f;
You can remove 50f and fixedDeltaTime here, they just cancel each other out

#

fixedDeltaTime is 1/50

#

50 * 1/50 is just 1

slim flower
#

hahaah thank you

heady iris
#

yes, and mouse input should not be scaled by deltaTime, anyway

#

it is an absolute quantity

slim flower
#

so what do i do abt this issue

#

do i just search through mirror?

leaden ice
#

i don't really know how it works

heady iris
#

i know you have to do that with Netcode for Game Objects, at least

#

but that's something else entirely

slim flower
#

i go through and register all prefabs in a resources/prefabs folder

#

thats not the exact dir but still you get my point

#

i dont get how to fix this though

heady iris
#

i would start by doing a sanity check

#

stick another random component on the prefab

#

see if that component shows up in game

slim flower
#

ok

heady iris
#

if it does, then it's probably not an issue with an old version of the prefab somehow getting instanced, or something

slim flower
#

yes it does

#

it does*

#

i fixed it

#

let me say the solution

#

for furture reference or similar issues

#

there are examples in mirror and in those exampeles there are premade scripts in games called the same as my own script, unity got confused betweent he scripts and saw the require conponent of the Character Controller and added it to my prefab.

#

basicly just delete the examples and change the name of the script fixes it

low horizon
#

how can i load an asset instantly when using addressables?

leaden ice
low horizon
#

didnt knew there was a channel for that

stone rock
#
        // Create a static instance of InputManager that can be accessed from other scripts
        public static InputManager Instance { get; private set; }

        private void Awake()
        {
            // If an instance of InputManager already exists, destroy this duplicate instance
            if (Instance != null && Instance != this)
            {
                Debug.LogWarning("InputManager: Duplicate instance detected. Destroying the duplicate instance.");
                Destroy(gameObject);
            }
            else
            {
                // If there is no existing instance, set this as the instance
                Instance = this;
                // Make sure that this object persists across scenes
                DontDestroyOnLoad(gameObject);
            }
        }

Hello, i wanted to get some more clarification into using events. so i have this singleton class for input with the logic to set it up in the awake method, below is the code of another script that needs to subscribe to this script.

        private void OnEnable()
        {
            InputManager.Instance.InputGearUp += OnGearUp;
            InputManager.Instance.InputGearDown += OnGearDown;
        }

        private void OnDisable()
        {
            InputManager.Instance.InputGearUp -= OnGearUp;
            InputManager.Instance.InputGearDown -= OnGearDown;
        }

Based on the documentation i would assume that the awake method for sure is called before on enable but i get a null reference exception

#

or is it done like this where awake and onenable are called after each other for each object and not first all objects their awake methods and then the onenable method?

leaden ice
stone rock
#

is there a reason it's done like that?

leaden ice
#

Definitely

#

I assume Awake -> OnEnable is just part of the initialization process for an individual script

#

But seeing as Unity is closed source and we're not privy to the code or the people who made it, we can only speculate

stone rock
#

Yeah, i guess i'll use start for the subscribing then

#

or maybe just also do it in start

leaden ice
#

or use script execution order

stone rock
#

yeah, but i first want to do it without any orders just changing the code

#

onenable is not called a lot so i will add a check for it

latent latch
#

So I've been making some abilities that spiral out from the player and it's been working out, but I'm trying to figure out for this code:


                objectDirection = targetPosition - relativeTransform.position;
                objectDirection = Quaternion.Euler(0, 90, 0) * objectDirection;
                objectDirection = objectDirection.normalized;
                posChange = ability.StatDict[AbilityStatType.AbilitySpeed] * Time.deltaTime * objectDirection;```
Changing Eulers here to anything below 90 will spiral outward, and anything above 90 will spiral inward with the current code, but at exactly 90 I expect the projectiles to hold their position in a perfect circular motion, yet after a few rotations they do gradually fall off course.
#

Is there anything I'm missing here to prevent that?

heady iris
#

it could be down to accrued error

#

even if it's only slightly off, the errors will pile up over time

latent latch
#

I know there's some floating point accumulations, but it falls off so quickly.

heady iris
#

I wonder if you could compute the position parametrically

#

that might be the wrong word

#

you'd have a function that you just plug the lifetime of the projectile into and get a position

#

i'm not sure what the math would look like, though

plucky karma
latent latch
#

Oh, also I manage to get the movearound method to work, I just had to multiply using the Rad2Degrees

#

object direction is initalized as vector3.forward

#

ah, yeah let me try that. I think I really tried everything like that so far

heady iris
#

hm, that could cause some errors, yeah

latent latch
#

Really it's closer to 89 degrees that really keeps it from going astray

#

Quaternion.AngleAxis(90, Vector3.up); behaves similar

plucky karma
#

You might have to perform some rounding logic to see if you are within 90 degree.

#

Otherwise, comparing exactly by precision value is unpredictable.

#

Are you calling this inside FixedUpdate()?

latent latch
#

Update

heady iris
#

oh! that's a good point

plucky karma
#

Try FixedUpdate() - Consider precaching Quaternion.Euler(0,90,0) since the value is immutable. No need to call it every update. 😄

#
private static Quaternion kCornerAngle = Quaternion.Euler(0,90,0);
latent latch
#

yeah ive got it cached, just typed what I'm doing ;p

plucky karma
#

Wait... untested code, not sure if I can call method inside static variable.

plucky karma
#

I think Update would be fine since you want to refresh position by frame dependent... Still, I think the problem is that you're going to be running into precision problem before your projectile could ever be perfect.

latent latch
#

Why exactly is MoveAround so pefect?

#

That doesn't seem to create any problems

heady iris
#

MoveAround?

latent latch
#

RotateAround*

heady iris
#

ah

#

RotateAround should just be doing trig

#

whilst you're moving the object in straight lines

#

now, in theory, those should be the same thing..

latent latch
#
                var lookDir = Vector3.Cross(targetPosition - transform.position, Vector3.up);

                transform.RotateAround(
                    sourceSpawnPosition,
                    transform.up,
                    Mathf.Rad2Deg * (speed / (ability.StorableSO.DistanceOffset / 2)) * Time.deltaTime);

                transform.rotation = Quaternion.LookRotation(lookDir, Vector3.up);```
#

works fine

#

I just kinda want the other thing to work with the spirals and the circular motion, but if it's just a precision thing then I guess it's not that big of a deal (don't want to deal with that right now)

#

Only problem is the look direction with this method is a little funky because by default it looks at the object it's rotating around

heady iris
#

yeah, it's annoying to have to have a special case

plucky karma
#

How are you making it orbit nearly 90 degree? What govern's the velocity?

latent latch
#

speed * Time.deltaTime * objectDirection

plucky karma
heady iris
#

what?

latent latch
#

I'll probably load up a blank project and play around with it more in case I've some hiccups somewhere in the code.

#

The SO page I mostly got the info from didn't really mention it working perfectly at 90, I'm just curious as to why it's not

candid trench
#

So i have the strangest bug happening to me right now.
I have a script with the OnDrawGizmosSelected() function defined.

Now, this does not work unless i go into the gizmos and tick the specific script first off and then on again.
And then it works for all of the gameobjects which has this script attached, but as soon as i switch to a gameobject, still with the same script attached, that is a child of another object then the gameobject i had selected when i turned the gizmo off and on again it stops working.

#

oh hang on a minute

#

do i need both
OnDrawGizmos()
AND
OnDrawGizmosSelected()
in my script for the selected version to work? o.O

quaint rock
#

the component has to be exapended

#

and the object has to be selected

#

if you only want it for selected OnDrawGizmos is not needed

candid trench
quaint rock
#

if the component that has the OnDrawGizmosSelected on it in the inspector is not expanded out so you can see everything it will not display

candid trench
#

ah, well i tried that, didnt do anything really.

#

But adding OnDrawGismoz() in the script, just empty, worked

quaint rock
#

weird what is the logic

#

sounds like it could be a bug, might see if there is a new minor update for your unity version

plucky karma
mighty granite
#

https://youtu.be/CmU5-v-v1Qo

This is a much better way of doing it. Line renderer just isn't made for complex UI things.

✅ Series Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53v5ur4GluoabyckImZz3TVQ
Grab the Project files and Utilities at https://unitycodemonkey.com/video.php?v=CmU5-v-v1Qo
In this video we're going to create a graph in Unity.
You can use this to display information in your game like amount of money earned per hour or guests visited p...

▶ Play video
plucky karma
mighty granite
#

Nope

prime pelican
#

hi, i have a question

#

I am trying to create a hud using ui toolkit
I created a text label, but I am not sure how to access it in my script

vagrant blade
keen warren
#

Looking for the best approach.

I have a quest system, one of the goals is to talk to an NPC. I listen for the NPCInteractEvent to achieve this but how I implement it has a side effect. The interaction event is fired before I deal with the dialogue then I check the goals status so I can display relevant dialogue but of course, side effect, quest gets completed before the goal check.

How would it be better to handle this? For added context, dialogue is handled via nodes. In a sense, the event would be better fired after interaction has finished but that may not always be applicable. Maybe there should be two events (interact start and end)? I'm not sure.

cosmic rain
#

Only completing quests on interaction sounds very limited.

keen warren
#

mmm actually true, it prevents dialogue where one option progresses to the next goal and the other doesn't.

#

although that may be better handled in the node graph for said npc or what have you, not too sure but you're right

sinful pivot
#

Hello everyone,

I'm having some trouble with my Scriptable Object in Unity. I'm trying to use it to store data for my game, whenever I enter play mode or restart Unity, the data is lost.

I am trying to create a Scriptable Object that allows me to easily specify the boundary rules for a procedural generation project. Here are my two scripts: the main script and the editor.

#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
 
[CreateAssetMenu(fileName = "New Prototype", menuName = "Prototype")]
public class Prototype : ScriptableObject
{
    public Tile tile;
 
    private Dictionary<int, bool[]> connections = new Dictionary<int, bool[]>();
 
    public bool[] GetConnections(int id)
    {
        if (!connections.ContainsKey(id))
        {
            connections[id] = new bool[4];
        }
 
        return connections[id];
    }
}
#
using System.Linq;
using UnityEditor;
using UnityEngine;
 
[CustomEditor(typeof(Prototype))]
public class PrototypeEditor : Editor
{
    private Prototype prototype;
 
    private void OnEnable()
    {
        prototype = (Prototype) target;
    }
 
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
 
        Prototype[] prototypes = AssetDatabase.FindAssets("t:Prototype")
            .Select(guid => AssetDatabase.LoadAssetAtPath<Prototype>(AssetDatabase.GUIDToAssetPath(guid)))
            .ToArray();
 
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("", GUILayout.Width(EditorGUIUtility.labelWidth - 4f));
 
        EditorGUILayout.LabelField("Right", GUILayout.Width(40f));
        EditorGUILayout.LabelField("Left", GUILayout.Width(40f));
        EditorGUILayout.LabelField("Up", GUILayout.Width(40f));
        EditorGUILayout.LabelField("Down", GUILayout.Width(40f));
 
        EditorGUILayout.EndHorizontal();
 
        foreach (var p in prototypes)
        {
            EditorGUILayout.BeginHorizontal();
 
            EditorGUILayout.LabelField(p.name, GUILayout.Width(EditorGUIUtility.labelWidth - 4f));
 
            bool[] connections = prototype.GetConnections(p.GetInstanceID());
 
            connections[0] = EditorGUILayout.Toggle(connections[0], GUILayout.Width(40f));
            connections[1] = EditorGUILayout.Toggle(connections[1], GUILayout.Width(40f));
            connections[2] = EditorGUILayout.Toggle(connections[2], GUILayout.Width(40f));
            connections[3] = EditorGUILayout.Toggle(connections[3], GUILayout.Width(40f));
 
            EditorGUILayout.EndHorizontal();
        }
    }
#

This results in the desired setup seen below.

#

I am able to check the boxes and see the updates, but the data is lost if I enter play mode or restart unity.

I've tried calling AssetDatabase.SaveAssets(), SetDirty(), and trying various methods to serialize the data, but nothing is working.

Does anyone know how I can fix this issue? Any help would be greatly appreciated.

prisma birch
#

Is there a way to correctly add a component using OnValidate? It's working but I'm getting this warning: SendMessage cannot be called during Awake, CheckConsistency, or OnValidate (GameObject: OnDidAddComponent)

#

Hoping to avoid a custom inspector

prisma birch
atomic bone
#

I'm trying to use

[Preserve]

to prevent reflection code from stripping but it is not working

#

all the reflection code seems to be still "missing" after the android build

#

it's IL2CPP

cosmic rain
#

I'm not sure reflection works in IL2CPP builds.

#

Since it's part of the .net runtime afaik.

#

According to the docs some of it works.🤔

#

I guess it needs to be checked on case by case basis.

amber haven
#

Plus I highly doubt that it would work overtop of a 3d camera which is the whole reason for a workaround anyway.

#

He seems to be making it for 2d, or for 3d use but on a separate camera which wouldn't work for me.

swift falcon
#
        if(deadBodies.Count >= maxDeadBodyCount)
        {
            for (int i = 0; i < batchRemoveCount; i++)
            {
                deadBodies.Remove(deadBodies[i].gameObject);
            }
        }

Would Running this statement in Update be a heavy task? I am unsure how fast Lists are

buoyant crane
swift falcon
swift falcon
buoyant crane
#

I wish it worked with more data structures

spare wing
#

Hi

#

any Visual Studios user here?

#

this is very useful extension for you if you use Visual studios

#

I hope its Helpful

swift falcon
#

@buoyant crane I cannot seem to get game objects from the Queue, cannot find much on google, I may need to just use Lists? (I need to destroy gameobjects from that queue)

buoyant crane
#

So you could do Destroy(bodies.Dequeue());

swift falcon
#

Thanks

#

Once again

atomic bone
#

it's just when you strip code at the highest level, it will be gone

latent latch
#

What's usually the more performative way to prevent multiple instances of damage to an entity in a time frame? Having a lookup table with IDs and with a previous time is the easy solution, but let's think about hordes of enemies where you've multiple abilities at your disposal.

real anvil
#

Have you benchmarked your current implementation and seen it be an actual problem?

latent latch
#

I've yet to really benchmark what I've got to the fullest, but this is more of a general question for its implementation. At the moment each of my abilities does contain a hashset which keeps track of previous hit enemies, but I'm getting to the point where I'm slinging many of those abilities all at once into waves of enemies.

real anvil
#

A hash table lookup is one of the cheapest ways to do this kind of tracking

pearl trench
#

how can I spawn objects randomly around the scene? I don't want them to spawn inside other objects

potent sleet
pearl trench
#

yeah but how do I make sure it doesn't spawn in other objects?

potent sleet
#

if blocked , spawn elsewhere

pearl trench
#

ok thank you

steady moat
modern meteor
#

hello

#

i have a Country class and a Tile class

#

there's going to be a static array/class of Tile instances

#

and a static array/class of Country instances

#

now i want each tile to store which country it belongs to

#

and each country to store a list of tiles it has

#

usually i use pointers, but this is C#

#

any ideas?

#

references wont work

#

public class Tile
{
    public int x;
    public int y;
    public Biome biome;
    public Country* country; // cant do this
}```
#

also, in the future i want to have a function that would look kind of like this: ```CS
public void DrawName(List<Tile*>, string name);

#

it also has pointers

split wedge
modern meteor
#

ah, thanks

#

there's no way that the pointer will be used after dereferenced btw (it's a pointer to member of static class)

#

oh, if Country is a managed type

#

what do i do?

quartz folio
#

Classes are reference types in C#, there is no need for a pointer

modern meteor
#

i'm pretty used to C and C++(was working on something else) so it's pretty confusing

quartz folio
#

Classes are reference types, structs are value types. Classes are allocated on the heap, and structs are allocated on the stack if they're defined in a small enough scope that allows for it

modern meteor
#

that's awesome

#

thanks

#

way easier now

#

wait, what about if you make an instance of a class locally

#

and then you call a method with it, then the method stores it somewhere else

#

the class wont be dereferenced right? because it's on the heap

#

so it's safe

atomic bone
quartz folio
#

You also have to mind clearing references to avoid leaks, which can be tricky at times with stuff like closures

modern meteor
#

really nice

#

thanks 🙂

atomic bone
#

i really wonder can you somehow impl const correctness in C# tho

#

i miss that thing so much

#

but then again, that's like just against the whole point of C#

#

idk

candid zenith
#

Anyone know how to make a Pathfinding Agent with Aron's A* Pathfinding stop getting stuck at corners? I am just at a lost.
This is on a 2D Tilemap

heady iris
#

I'm guessing the problem is with how you move the agent, rather than with how the path is calculated (A*)

candid zenith
#

I just have A* move the agent for me, I guess? Default settings, except for Pick Next Waypoint Dist which was lowered due to the Agent trying to go through walls.

normal arch
#

so i have to make a change to my project so that all things that have sprite renderers in my project have to have them be a separate child game object from the parent object and i have to change all the animations so that they are on the right sprite renderer. Is there a quicker way to do this because it's becoming very tedious

heady iris
#

You can edit the path for an animation channel directly. That might help if you’re making the same change for every single channel

#

I’ve done that for my VRC avatar when moving parts around

normal arch
#

how would you do that

heady iris
#

so I made an animation that controls the scale of the "Path" object

#

if I hit Enter (on macos; it's probably F2 on windows), I can edit the target of that channel

dense canyon
#

How can I play an audio file from disk? All google posts I've found point to a WWW class which is deprecated.

dense canyon
#

for URI do I pass in the raw filepath or do i need to add something else?

heady iris
#

I would expect to need to use the file:// protocol

dense canyon
#

thanks

heady iris
#

but this is spitballing :p

halcyon gull
#

Just 3 months ago I created a game using Unity Mediation package and got a good grasp of how to write code. Now I wrote similar code for my new project just to find out that Unity swapped that Mediation package with some LevelPlay that works with IronSource.

Why does this change so often and should I expect LevelPlay to change again anytime soon?

fathom totem
#

The inputs in the new input system, what are their refresh rate? (Such as when using Pass-Through and ReadValue<>)

#

Would ReadValue return the last input registered from the hardware polling rate, the input from the last frame update, or from the last physics update?

fathom totem
#

Ah, thank you, don't know why I couldn't find that

wary wagon
#

Hey, i want to draw a minimap of my game. Basically i just want to draw some rectangles and layout of the map.
I am thinking of using Texture2D .. however this is reaally slow, i want to avoid drawing every pixel ( especially wasting CPU filling all the image with transparent pixels).

Is there a better way ?

leaden ice
static matrix
#

is it possible to make a button do something different on rclick rather than normal click

static matrix
#

how

leaden ice
#

Use IPointerClickHandler instead of the button on click

#

or event trigger

#

and the pointer event data contains info about which button it was

wary wagon
static matrix
#

uuuuuuuuuuuuuuugh Im too tired to learn something new haha

Imma make a smaller button for dropping

#

sorry

#

ill get back to it

heady iris
#

you can set many pixels at once with SetPixels

#

this is reasonably fast

wary wagon
#

Im gonna prepare a Color32[] buffer full of transparent and .. yea.. do setPixels

static matrix
#

yeah, sorry i didn't know if it was possible using the normal button

#

its cool

#

my b honestly

wary wagon
#

Basically lol i want to use Gizmos to create my minimap xD

heady iris
#

aren't gizmos editor-only

wary wagon
#

Ya, but i want non-editor gimzos ;D

olive shore
#

im sorry, but has anyone got any know how on this?

Building Library\Bee\artifacts\Android\d8kzr\libil2cpp.so failed with output:
ld.lld: error: undefined symbol: GADUGetAdErrorCode

static matrix
#

its an error alright

wary wagon
#

so mm what would be the best to mimick gizmos outside editor 🤔

jagged latch
#

i have this code to automatically make a PolygonCollider2D in the shape of a circle sector, as such, but i would like some way to mask the sprite programmatically so that what you see in the collider is the only bit that's shown. how would i go about doing this? (it doesn't have to use the collider, but just some way to mask a sprite in a sector/arc with a customisable angle)

static matrix
wary wagon
#

scratch pen ? 😮

static matrix
#

nah its a scratch thing

#

the funny orange cat

#

imma let you be now, back to the backrooms

heady iris
#

Scratch support for unity when?

#

💥

#

visual scripting 2, baby!

wary wagon
#

🤔 maybe i should just access opengl low level stuff so i can draw fast triangles on the screen ? that will be faster than bothering with texturing the minimap

leaden ice
#

just make sure the minimap camera only renders obstacles etc and doesn't render the ground

wary wagon
#

The issue is that i mask the rooms on which my player is not ( i have a tileset that draws black tiles ) .. so the minimap will be black ?

leaden ice
#

just don't draw that tilemap in the minimap camera

wary wagon
#

Ahh i can do that ? fun

leaden ice
#

yes using culling masks

wary wagon
#

ok ! going to check this

#

Ideally i just want to render the walls

#

mm now i need a way for the camera to not render what the player hasnt visited yet .. hard ;D

heady iris
#

i'm guessing you want to do this per-room, though?

#

slap a trigger on the room that the player interacts with

wary wagon
#

basically .. i want to show the full layout of a dungeon for the room the player has visited.

#

haha now im thinking to have a tileset that is rendered only on the minimap.. i can do this 😄

heady iris
#

It might be slightly harder if you want the rooms to always appear in the main camera, but only get put on the minimap if you've actually been in them

wary wagon
#

in the main camera i dont want to show the rooms in which the player is not

#

For gameplay ( i expect monsters to ambush the player) and perf reasons

worldly hull
wary wagon
#

yeah i will do it

timid crater
#

Good afternoon! is there a way to read an element from the queue without dequeuing(removing the element)?

timid crater
#

I tried Dequeue(); before but it removes the element from the queue

heady iris
#

peek, right?

#

yeah

timid crater
#

Ohhh that what I was looking for, thanks!!

jolly sparrow
#

Can anyone help me out? Can't figure out to move an object move perpendicularly to my movement when i collide with it, on 2D

heady iris
#

do you mean you want it to get pushed directly way from the player?

jolly sparrow
#

like if i move into an object from the left side it will be pushed vertically to the top or or down, etc

heady iris
#

ah, okay, so actually perpendicularly

#

i wasn't sure if you meant something else :p

jolly sparrow
#

i edit the sentence, i missed a word when i was typing

heady iris
#

well, let's see

#

so you need to find a vector that's perpendicular to the player's movement vector

#

Vector3.Cross will do the trick

#

The cross product can best be visualized as

#

A is gonna be your movement vector

#

B is the "forward" vector (the one going into the screen)

#

and then AxB will be the result

#
Vector3.Cross(rb.velocity, Vector3.forward);
#

alternatively, you could rotate the velocity vector

#
Quaternion.Euler(0, 0, 90) * rb.velocity;
#

I think that one make sit more obvious which way it will go

#

it's a 90-degree rotation

fervent furnace
#

https://en.wikipedia.org/wiki/Rotation_matrix
maybe this is helpful but there already is a built in function

In linear algebra, a rotation matrix is a transformation matrix that is used to perform a rotation in Euclidean space. For example, using the convention below, the matrix

    R
    =
    
      
        [
        
          
            
              cos
              ⁡
              θ...
#

and cross product is defined in 3d space, but you can treat z is 0

heady iris
#

yes, there's no need to figure out transform matrices here :p

heady iris
#

fortunately, what we want is the cross with the (0,0,1) vector

wide verge
#

Anyone know how to save an int value (to read from on next play) from another script?

heady iris
#

on next play meaning "the next time the game runs"?

jolly sparrow
#
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            Vector2 pushDirection;

            if (Mathf.Abs(movementVector.x) > Mathf.Abs(movementVector.y))
            {
                // If moving mostly horizontally, push enemy up/down
                Vector3 perpVector = Vector3.Cross(rb.velocity, Vector3.forward);
                pushDirection = new Vector2(perpVector.x, perpVector.y).normalized;
                Debug.LogError("Player Moving Horizontally:" + pushDirection);
            }
            else
            {
                // If moving mostly vertically, push enemy left/right
                Vector3 perpVector = Vector3.Cross(rb.velocity, Vector3.forward);
                pushDirection = new Vector2(perpVector.x, perpVector.y).normalized;
                Debug.LogError("Player Moving Vertically:" + pushDirection);
            }

            collision.gameObject.GetComponent<Rigidbody2D>().velocity = pushDirection * pushForce;

        }
    }``` @heady iris changed my previous code and ended up with this, but the object still wont be pushed away
heady iris
#

Do you want it to snap to the axes?

#

i.e. it only goes up, right, down, and left

fiery geyser
#

how can i check if two colliders are intersecting, 1 box collider and 1 non convex mesh collider

heady iris
jolly sparrow
heady iris
#

I'd just use OnCollisionEnter and OnCollisionExit to keep track

heady iris
fiery geyser
#

i need to check when it spawns

heady iris
#

ok, hang on

#

what is the usecase?

fiery geyser
#

i have 2 structures, and i need to check when another spawns, if it is intersecting one of them

jolly sparrow
# heady iris well, yeah, both blocks of code are identical!
private void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            Vector3 perpVector = Vector3.Cross(rb.velocity, Vector3.forward);
            Vector2 pushDirection = new Vector2(perpVector.x, perpVector.y).normalized;
            Debug.Log("Direction:" + pushDirection);
            
            collision.gameObject.GetComponent<Rigidbody2D>().velocity = pushDirection * pushForce;
        }
    }
```oh yeah, but still, the object **isn't** being pushed away perpendicularly
heady iris
#

since you said one is a box, though

#

you can just use Physics.OverlapBox to ask for colliders in an area

fiery geyser
#

even if i don't have the reference of the other two?

heady iris
#

right, it just asks if anything (on the specified layers) is in there

fiery geyser
#

oh ok

#

let me try

#

oh wait

#

i did try the overlap box

#

Physics.OverlapBoxNonAlloc(bounds.center, bounds.extents, new Collider[] {}, Quaternion.identity)

#

but didn't work

heady iris
#

if you don't understand what NonAlloc means, do not use it

#

just use Physics.OverlapBox and loop over the array of colliders

fiery geyser
#

it was suggested by Rider

heady iris
#

Rider can suggest many, many things, but most of them are the wrong choice :p

wide verge
#

Anyone know how to save an int value (to read when the game is next ran) from another script?

fiery geyser
#

oh ok

heady iris
wide verge
heady iris
#

again

#

use PlayerPrefs.

gray vessel
#

Is there any way to change a component to an inherited version of itself? I had a bug script, and I want to retain the inspector properties, of which there are many, when changing it to an altered, inherited version. Previously, you could change the Script field in debug mode, but they seem to have blocked that off

wide verge
heady iris
#

oh, I see

#

I thought you were asking about having the other script get the saved value

#

well, you have a reference to the stopwatch script, right?

#

if so, you can access any public field of the stopwatch script

heady iris
#

and drag the stopwatch object into the resulting field

fiery geyser
#

thx, it was the NonAlloc

heady iris
#

if you are curious

#

NonAlloc means that the method does not allocate its own memory. Instead, you give it an array you made yourself.

fiery geyser
#

ohhhh

#

that's why

heady iris
#

This means that it's not creating and destroying an array every time you use it, which can matter if you're worried about creating too much garbage

#

i.e. memory that was allocated and then thrown out

#

For example, I use it when I just need to check if something is in an area

#

and I give it a one-element array

#

I would only worry about that if you're doing this many many times per second

#

if it's just for when an entity spawns, and you spawn a sane number of them, don't even bother

fiery geyser
#

depends on how fast the player is moving, but shouldn't spawn a lot of them

#

and just intersect max 4 things

jolly sparrow
#
private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            Vector3 perpVector = Vector3.Cross(rb.velocity, Vector3.forward);
            Vector2 pushDirection = new Vector2(perpVector.x, perpVector.y).normalized;
            Debug.Log("Direction:" + pushDirection);
            
            collision.gameObject.GetComponent<Rigidbody2D>().velocity = pushDirection * pushForce;
        }
    }
``` @heady iris its working now but i have 2 problems, the object will only be pushed away in a clockwise rotation and it is only pushed away if the Enemy Object isn't moving so my script of the Enemy Object Movement with ```csharp
private void FixedUpdate()
    {
        Vector3 direction = (player.position - transform.position).normalized;
        rb.velocity = direction * velocity;
    }``` on the Enemy object to make it follow me has to be disabled for to Object to be able to be pushed away
heady iris
#

well, yeah, you're overwriting the velocity on every fixed update

#

perhaps the enemy should either get "stunned" and not move after getting hit

#

or it should gradually adjust the rb's velocity

jolly sparrow
#

what about the clockwise rotation

heady iris
#

maybe the enemy is pushing into the player and turning as a result

#

you can check something on the Rigidbody component to freeze rotation

#

that might be useful

jolly sparrow
#

Sorry, should have explained better, what i mean is that the object is being pushed away in a clockwise direction around the Player Object, so if i collide with it from the left side he will be pushed down, etc
from above -» to the left side
from the right -» up
from under -» right

heady iris
#

ah

#

isn't that what you wanted?

jolly sparrow
#

The idea is that if im for example, surrounded by enemies and i want to pass through them, they will be pushed away perpendicularly to my direction so that i can move through, and it would be weird if it only worked on a clockwise direction like this

heady iris
#

so you want them to get pushed up or down depending on whether you're above or below their center?

#

and only get pushed in the cardinal directions?

jolly sparrow
#

if they are to my sides they will be pushed down or up, if they are up or down they will be pushed to the sides, depending on which direction i try to pass through

#

it would also have to work in diagonal directions i guess so i can move that way, but baby steps, was trying to get the other directions right first

#

@heady iris sent you a clip on dm

heady iris
#

just make a thread in here, please

jolly sparrow
#

2D - Pushing objects away to allow passage

swift falcon
#

Any thoughts on how to implement floating unit icons as in Warno? So that even if units overlap, the icons will never overlap?

heady iris
#

i think i ran into this before...

#

hmm

#

you could do it with Actual Physics

#

with 2D rigidbodies (with some serious limits on how fast they can move :p )

swift falcon
#

how so? sounds interesting

#

just standard collision behaviors would constantly jitter back and forth no?

sleek bough
gilded bramble
#

sorry

heady iris
swift falcon
#

is there a smoothing variable?

heady iris
#

actually, one thing -- are those units part of a squad of some sort?

#

i.e. they're always together

#

that might make it easier

swift falcon
#

I mean, no, mechanically it's just single units

heady iris
#

but you'd still want to have the icons stick to the individual units when you zoom in close enough..

sleek bough
heady iris
heady iris
swift falcon
#

UI grid specifically seems nice

mint estuary
#

Hey ppl, on Unity if i have two Monobehaviors object, referencing the same instance of another gameobject

ClassTest1
-----> ClassBase
ClassTest2

if ClassTest1 and Class2 execute the function

ClasseBase.SetValue()
var value = ClasseBase.GetValue()

can happen that Before ClassTest1 receive GetValue(), ClassTest2 have it changed too?

inland escarp
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

leaden ice
heady iris
#

they're asking if both scripts could call SetValue before one of them calls GetValue

heady iris
#

this cannot happen; the scripts on the objects will get updated in sequence

#

even if you spawn off some coroutines and have them mess with the value, they will also run in sequence

mint estuary
#

oh, ok them, thank you @heady iris !

#

@leaden ice thanks too

fiery geyser
#

why gameObject.transform.rotation.y is returning 0.7018 when the rotation is 90 on the inspector?

simple egret
#

Because .rotation is a Quaternion value, something that represents a rotation in a very abstract way

#

4 float values, ranged from -1 to 1

fiery geyser
#

so, how do i get the real rotation?

simple egret
#

.eulerAngles

fiery geyser
#

oh ok

leaden ice
simple egret
#

That spits out angles in degrees

leaden ice
#

it's generally not a good idea to read euler angles back from a Transform in code except for display purposes though.

charred geyser
#

This might seem dumb, but I'm having problems with rotating in 2d to the mouse. So, how to do that?

fiery geyser
#

i just need multiples of 90

#

btw, is there a way to make float operations more precise?

leaden ice
leaden ice
elder otter
#

Sort of. You can use double but Unity doesn't use it internally so it has limited use

charred geyser
#

I did that, but my character just gets its front to that direction, making it look paper thin

heady iris
leaden ice
#

show your code

#

sounds like you did forward not right or something

#

or directionToMouse was calculated improperly

charred geyser
#

Correct, but it was something else

leaden ice
#

e.g. with a nonzero z value

charred geyser
#

Turns out I used transform rather than render.transform (render is an object for the sprites)

#

How do I make objects not collide with objects of a certain layer?

#

I already did the layer thing, but it didn't work

leaden ice
#

Layer based collisions

charred geyser
#

I did that

leaden ice
#

you must have done it incorrectly

#

show what you tried

#

also make sure you used 2D physics settings if you're using 2D physics

charred geyser
leaden ice
#

Is this 2D or 3D?

charred geyser
#

Thank you

charred geyser
#

How do I get lightweight render pipeline? I can't search for some reason

leaden ice
#

It's called URP now

#

Universal Render Pipeline

charred geyser
#

Oh, ok, thank you

subtle glade
#

Has anyone ever used patch obb files for their Android projects (eg patch.1.com.myapp.demo)?

fallen crow
#

Hello, not sure if this is the right channel, but I'm having a bit of a problem with Mirror and Networking inside my project.
I'm using a Steam based P2P system, only two players. Each player has a parent object which gets filled with Instantiated prefabs.
Now i want a function, that "copies eachothers prefabs" into our parent, so our unique prefab list merges on both clients.
How should I get started with this?

fathom patrol
#

Any idea why my Serializefield area isnt popping up?

#

Code:

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

public class MapArea : MonoBehaviour
{
    [SerializeField] List<Enemy> wildEnemys;

    public Enemy GetRandomWildEnemy()
    {
        return wildEnemys[Random.Range(0, wildEnemys.Count)];
    }
}

#

I have no errors so I dont understand why its not popping up

leaden ice
#

Is it serializable?

fathom patrol
#

im so dumb, no its not

#

thanks

sonic zinc
#

I want to grab an entire canvas mainly so I can set .enabled to true and false
putting the canvas in a GameObject doesnt seem to work so what variable do I put it in

leaden ice
#

if that gives you an error message - read the message as it has important information for you, and check what auto-fix suggestions your IDE has for you.

sonic zinc
#

it sort of works, it unpauses but it cant pause @leaden ice

leaden ice
#

look at your code

#

shouldn't that if be an else if?

sonic zinc
#

am I missing something obvious

leaden ice
#

yes

#

the second if will run right after the first one

#

they're independent

sonic zinc
#

oh thanks

#

I never use else if and end up using 2 ifs

#

it works now

leaden ice
# sonic zinc it works now

better code for this:

void Update() {
  if (Input.GetKeyDown(KeyCode.P)) {
    paused = !paused;
    Time.timeScale = paused ? 0 : 1;
    uiPause.enabled = paused;
  }
}```
#

no need for the duplicated code.

sonic zinc
#

Time.timeScale = paused ? 0 : 1; //how does this line work exactly

#

@leaden ice

leaden ice
#

it sets time scale to 0 if paused is true, 1 otherwise

sonic zinc
#

alright thanks for all of the help

sonic zinc
hardy anvil
#

I have implemented a FSM for walking, jumping, attacking etc where all are different states. Is this a bad approach for game design as most of the time things are overlapping? The user should not notice these, after all

leaden ice
#

and show the inspector

sonic zinc
#

I got it to work now

#

what I did was enable the canvas in my inspector but disable on void start

cosmic swallow
#

Greetings,
I have a editor window script that references a TextAsset. I want to open the TextAsset at a specific line-number in vscode. I'm using the method AssetDatabase.OpenAsset(). It does work properly for .txt files.
However, I have created a custom file-type ".aljs". I created a ScriptImporter that imports those files as TextAssets. I have a custom vscode extension for this file-type for syntax highlighting. AssetDatabase.OpenAsset(). opens the correct file, but it does not jump to the correct line. The documentation (https://docs.unity3d.com/ScriptReference/AssetDatabase.OpenAsset.html) "If it is a text file, lineNumber and columnNumber instructs the text editor to go to that line and column."
Is there a way to make it work for my custom file-type?
I have a workaround in place, but it's kinda bad. It starts a process before which opens a console window for short and it's kinda slow.

string filePath = AssetDatabase.GetAssetPath(textAsset);
string fullPath = Application.dataPath + filePath.Substring("Assets".Length);
System.Diagnostics.Process.Start("code", "-g \"" + fullPath.Replace("\\", "/") + "\":" + 15);
AssetDatabase.OpenAsset(textAsset);

Does someone know how to make it work without having to start an additional process?

Kind regards.

lament bloom
#

I have a "sheath" animation that my character is engaging in here, but this involves reparenting the sword from the character's hand to their back. the animation runs in a coroutine while the reparenting is done imperatively, i'd just like to know what the most straight-forward/idiomatic way to do the reparenting at the right moment in the animation would entail. should i just try and figure out exactly how many (milli)seconds into the animation is the right time for the reparenting to occur and then do the reparenting in a coroutine that waits that long before starting?

severe marsh
lament bloom
#

wow that rocks, thanks so much glad i asked

marble halo
#

So i'm trying to use a tilemap for the in game map, for some reason some of the white edges dissappear in game

#

notice in the top right how the rectangle doesnt have the bottom edge like in the editor

leaden ice
marble halo
#

no

#

that might be why

leaden ice
#

you should be

marble halo
#

btw is using a tilemap for a map a good idea

#

I thought of doing it cause it would make it easier to make levels

#

why cant the pixel perfect camera rotate down?

marble halo
#

Is it cause im in 3d?

leaden ice
#

wdym by "in 3d"?

#

you should be using an orthographic projection on your camera if it's a 2D game, if that's what you mean

marble halo
#

my game is 3d also it says that render texture doesnt support the pixel perfect camera

acoustic scroll
#

I'm getting weird stuttering with Cinemachine. I've got some camera math that updates in FixedUpdate and then interpolates in LateUpdate, which is important for the kind of high-speed type of game that I'm working on.

This works perfectly in raw code, but every time I try to get Cinemachine to run it, even when I'm updating all the data manually. I've tried switching the update method and calling ManualUpdate from within LateUpdate.
Something about Cinemachine's internals or the MutateState function must be failing to apply the camera transform properly. Does anyone know what could be causing it?