#archived-code-general

1 messages · Page 166 of 1

jaunty sleet
#

you don't call them

#

Also, does anyone know why this code:```cs
void Update()
{

    if (!menuControlsEnabled) return;

    if (Input.touchCount > 0)
    {
        Debug.Log(EventSystem.current.IsPointerOverGameObject(0));
    }
}
#

I can't seem to get this to work for me

#

the menu controls part is irrelevant btw its just the event system one

sick flint
#

I'm not using monobehavior so idk if that is an issue but the inputaction works without enabling the script

somber nacelle
indigo arrow
#

A little issue I've ran into is that I can't add any children of BaseUpgrade to the availableUpgrades list in the inspector. Do you know why this could be?

jaunty sleet
somber nacelle
sick flint
#

sorry I am, I am lying I am using a namespace that uses monobehaviour

rocky basalt
#

For RotateAround(), how do you control how far away from the center/point the rotating transforms are? Like in terms of radius

somber nacelle
somber nacelle
jaunty sleet
#

It is enabled by scripts when I run the game btw

somber nacelle
#

you can view what the event system is detecting in the inspector. so check that. then if it isn't detecting the object maybe ask in #📲┃ui-ux

jaunty sleet
somber nacelle
#

should be in the preview window at the bottom of the inspector window

#

look at it during play mode

jaunty sleet
somber nacelle
#

yes

jaunty sleet
#

huh, theres nothing there

somber nacelle
#

do your buttons work

jaunty sleet
#

Yes

somber nacelle
#

then if the object is still not being detected when it is set active you should post your setup for your UI in #📲┃ui-ux to get help there

jaunty sleet
#

oh, when I click something it goes into selected. I'm just dumb lol

brittle sparrow
#

is this a suitable channel for profiler questions? My game tends to produce lag spikes out of nowhere, and it comes from the "Other" category in profiler. What kind of stuff tends to fill up this category usually? I was thinking Editor, and it would be nice if it were editor, because i wouldn't have to make any tweaks. Any ideas?

rocky basalt
#

You will often notice the frame immediately after is shorter. So it may be a minor bug in the Profiler

#

Attributing too much time to one frame. That's my theory anyway

lean sail
pure cliff
#

So I have this challenge I need to start tackling soon, I posted in #📲┃ui-ux in case there was a non-script solution, but Ill also share the link to it here to hear folks thoughts on what the script solution outta be.

I feel like I gotta do something like get the images normal aspect ratio, math out the exact X/Y/Scale values for the box, and reposition it manually with script which sounds like a pain
<#📲┃ui-ux message>

#

Am I on the right track there? or is there an easier approach?

rocky basalt
#

@brittle sparrow if the extra time is showing below "Self MS" of the PlayerLoop top-line in hierarchy, then it's the same issue I'm talking about

brittle sparrow
#

thank you very much everyone! i'll try everything right now

rocky basalt
#

yes

lean sail
# brittle sparrow this?

Yea then itll bombard you with info, but the very top of the hierarchy will tell you editor or player loop. You can also sort by what took the longest

brittle sparrow
#

ohh that

#

it's playerloop

#

oh.. so it's my code then..

#

or this

#

whatever it is

#

full expansion

rocky basalt
#

From your first image, seems the spikes are relatively small, and you're still well under your target FPS right?

I'd honestly not worry about it for now unless you see something really bad in the hierarchy.

Those images don't help us much if you don't include the part showing the MS time

brittle sparrow
#

it shows a ~160ms clip

rocky basalt
#

oh i didn't see it was that big. yeah, you want to dig into the hierarchy tab and see if any insight

brittle sparrow
rocky basalt
#

If it's just Other and you cant find any clues, then it might be something in your code

brittle sparrow
#

remember*

lucid valley
#

screenshot the full profiler, hard to judge performance otherwise

brittle sparrow
#

i'll get a good lag spike to display then

#

alright, this is weird but although I got an Other lag spike before, I got a Script lag spike this time, i'll hunt for another lag spike after this but here's take #1

lucid valley
#

you'll need to expand the top ones

brittle sparrow
#

it kind of stops there

#

not sure

#

maybe it has some hidden elements i need to toggle on?

rocky basalt
brittle sparrow
#

ohh okay

lucid valley
#

just be careful, can eat your RAM up and crash Unity if you have a large project

brittle sparrow
#

nope, dead end

#

oh, my project's relatively small

lean sail
#

502b is a lot of alloc

brittle sparrow
#

502 bytes, how do i know what code allocates memory?

lean sail
rocky basalt
#

Well something is clearly going on involving Sprites

lean sail
#

Some update loop is doing a lot of alloc

brittle sparrow
#

this is all i could fit

rocky basalt
#

are you instantiating or destroying Sprites?

brittle sparrow
#

"Sprite" is just another term i use for "Object"

indigo arrow
#

I'm having an issue where in I want to have a "List<BaseUpgrade> availableUpgrades", but do not want the BaseUpgrade class to have to be attached to an object. At the same time, the list won't show up in the inspector if BaseUpgrade doesn't derive from MonoBehaviour. Any ideas on what to do? Am i being silly and missing something?

brittle sparrow
#

it's a special gameobject that uses an abstract class Sprite that uses MonoBehaviour

lucid valley
#

oh, you have made a monobehaviour called sprite?

brittle sparrow
#

yeah

#

it helps a lot with extra stuff

lucid valley
#

show the Update code

rocky basalt
#

there seems to be something in your code where all those objects are doing a bunch of work on the same frame.

lean sail
brittle sparrow
#

my Update is actually a virtual function, so a lot of functions use it

#

i think it's the Player function though

brittle sparrow
#

might be my monitors

#

i'll try disabling them

#

my monitors keep track of some variables and print them

lucid valley
indigo arrow
#

Is there no other way

rocky basalt
lean sail
indigo arrow
#

twice as many BaseUpgrades

rocky basalt
brittle sparrow
#

so much potential, pretty worth it

#

it doesn't use a class, so it won't show in profiler

indigo arrow
brittle sparrow
#

wait, it does actually

rocky basalt
brittle sparrow
#

does Debug.DrawRay (for raycasts) cause lag?

#

it was in my code

#

probably was being called over 10 times

brittle sparrow
#

per frame

#

or 5

pure cliff
#

My rule of thumb is always "If the <thing> doesnt have a transform and doesnt exist in world space, it doesnt need to be a monobehavior"

rocky basalt
swift falcon
#

Hello i need some help with my project that in a certain radius, the character presses e, and then something happens

#

But I don’t know how to do it

#

I searched for a lot of tutorials

#

Like a lot

indigo arrow
pure cliff
peak thicket
swift falcon
swift falcon
#

I’m not too sure

rocky basalt
indigo arrow
# pure cliff Why do you need it in the inspector

because its a list of upgrades the player can have. When the player levels up, x amount are chosen at random to be a choice for the player. By having it in the inspector it makes it easy to create new upgrades and then add them to the availableUpgrades list

peak thicket
swift falcon
rocky basalt
pure cliff
#

Using an Enum as your identifier to select your applicable upgrade object

somber nacelle
#

man you really like that strategy pattern, huh?

indigo arrow
pure cliff
indigo arrow
#

which scriptable objects cant have from my knowledge

rocky basalt
pure cliff
#

Pretty much anytime you have "I have a shit tonne of doohickeys that are sorta the same and you can apply them in some way to mutate state" thats strategy pattern.

Inventory items? Strategy pattern.
Equipping items? Strategy pattern.
Enemy behaviors? Strategy pattern.
Objects that can exist in the world and behave different ways? Strategy pattern.
Character upgrades / abilities? Strategy pattern

etc etc

#

particularily when said doohickeys have something in common but also something unique, so you need some common logic + some unique logic per doohickey

indigo arrow
lucid valley
indigo arrow
#

The DoUpgrade function is overriden in each child of BaseUpgrade and so do different things

pure cliff
lucid valley
mossy snow
pure cliff
#

SO still doesnt make sense, there's no reason for your "ability upgrade" conceptual thing to have a transform

#

just use a POCO

mossy snow
#

? SO do not have transforms, they're not components

pure cliff
mossy snow
#

no

pure cliff
#

ah aight then

#

they also still have stuff like Update and whatnot though no?

indigo arrow
mossy snow
#

no

pure cliff
#

all that stuff also isnt needed

lucid valley
#

not Update

pure cliff
#

so whats the difference between an SO and a static class?

#

it just lets you add it in the inspector?

indigo arrow
#

From what I know, SO only exist to contain variables and data, not functions

pure cliff
#

my main gripe is SOs also wont be abstractable, you cant interface em and ref the interface instead for your referencing game object

lucid valley
#

SO's are for storing immutable data, easily changed using the inspector; they can have functions like any other class

somber nacelle
pure cliff
#

which means you tightly couple your logic to the concrete class, which makes it way harder to do mocking and whatnot for testability

somber nacelle
#

why would you compare something that requires instances to a static class?

pure cliff
#

Isnt it literally a static method you use to get the SO "instance" anyways

#

its like a weirdly obfuscated pseudo static (but not) class

indigo arrow
#

My problem is that I need it to be generalised. So i can simply call a certain function from the list like currentUpgrades.DoUpgrade(), and abstract classes allow this

pure cliff
#

it just seems to weirdly "Im gonna do 8 steps to re-invent the POCO"

indigo arrow
#

Because the DoUpgrade() is different in each child class

#

which wouldn't happen with SO

mossy snow
#

I think maybe you should read up on SOs

lucid valley
pure cliff
#

from what I have seen... SOs seem like a lot of extra steps when you can just use a POCO and DI

mossy snow
#

you'd be terribly mistaken

somber nacelle
indigo arrow
pure cliff
#

I dont see the appeal for SOs aside from "now you can drag and drop it into a serialized field" which is a lot of work to do to avoid just writing clean and simple C# code

somber nacelle
#

you can have an instance of a scriptable object as an asset in the project. you cannot do the same with a poco

lucid valley
peak thicket
#

My understanding was that SOs were just convenient containers for data storage

dusk apex
pure cliff
pure cliff
pure cliff
#

like yeah obviously at the compiler level they are different

#

but Im talking about how are they different in terms of the code you end up with

rocky basalt
#

I mean SO retain data between runs, which might help PQ because they seem to be using a prefab for every configuration of their class

indigo arrow
dusk apex
#

They aren't the same in any way. One defines a type. The other is simply data that can be filled in using the inspector.

lucid valley
#

with SO's you can change values during playmode and have it effect immediately without a stop and code compile, great for testing

somber nacelle
peak thicket
#

oh, Plain Old Container Objects?

oblique briar
#

Does anyone know any up to date tutorials I can follow to do my first code? All of the ones I look for are all out of date

pure cliff
dusk apex
#

I would think of SO as more like a regular class or struct that's accessible from the inspector (a field)

pure cliff
dusk apex
#

How's this relate to static though?

pure cliff
#

its a tightly coupled static relationship

dusk apex
#

What? Immutable?

pure cliff
#

Sure its technically an instance, but the point is you are 1:1 tightly coupled to the concrete now

indigo arrow
pure cliff
oblique briar
somber nacelle
#

the api has not changed that much

dusk apex
#

Hopefully no one associates static with global.

pure cliff
#

Like you cant (easily without doing wild stuff with reflection) mock it

indigo arrow
#

Sooo how would I go about doing my availableUpgrades list then

#

Like this, I need to be able to set the availableUpgrades in the inspector, but I either need to have the script on a gameobject, or the list doesn't show up if it doesn't derive from monobehaviour

mossy snow
pure cliff
# indigo arrow Sooo how would I go about doing my availableUpgrades list then

Strategy pattern is effectively:

  1. You want some overhead parent service, a "manager" if you will, that has the list of all your strategies, ideally in the form of a dictionary
  2. Your strategies simply implement an interface, including an exposed getter prop of what strategy they are (I usually define this via a Flagged Enum, if you want stuff to have multiple strategies, dont flag it if stuff can only have 1 strategy at a time)
  3. Your prefabs just have a serialized field for the Enum, which is a dropdown, to pick what strategy(ies) they have
  4. You have a further parent service that has the "common" logic they all posses, and then it hands off the "unique" logic to the strategy as needed (grabbed via the manager)
proper olive
#

You’re unintentionally overcomplicating your system

lucid valley
indigo arrow
#

plus it seems inefficient in the way the gameobject with the script method was inefficient

#

each different upgrade would have to have its own scriptableobject

peak thicket
dusk apex
# pure cliff the issue is the tightly coupled 1:1 problem

It's interchangeable through the inspector. Assuming referencing through the inspector (drag and drop) is simply referencing, it's a plain ol instance placed elsewhere. It's not a part of the type that references it. It's not defined as a part of it. A prefab with it referenced isn't a type in my opinion but a compound of data.

indigo arrow
peak thicket
#

I guess its just two ways of doing the same thing, but more decoupled from a central manager class?

pure cliff
#

Theoretically your code should be something like:


public class ThingDoer
{
   private StrategyManager StrategyManager { get; }
   public ThingDoer(IStrategyManager strategyManager)
   {
       StrategyManager = strategyManager;
   }

   public void DoTheThing(Entity myEntity)
   {
      // Could be "strategies" if you intend to support multiple and foreach
      var strategy = StrategyManager.Get(myEntity.Strategy);
      DoSomeCommonLogic();
      strategy.DoSomeUniqueLogic();
      DoSomeMoreCommonLogic();
      strategy.DoSomeOtherUniqueLogic();
   }
}

@indigo arrow

pure cliff
rocky basalt
# indigo arrow Why do you say so

Why not get rid of your inheritance, have everything be an Upgrade, then have an enum for each "type", and on Start/Awake, set the properties based on its enum

pure cliff
#

Inheritance can seriously muck up your order of "wait where did this happen"

peak thicket
#

Hmm fair enough

indigo arrow
pure cliff
lucid valley
#

I can see the benefits of both ways, but if you 100% want editor inspector functionality then Scriptable Objects would be easier imo

indigo arrow
peak thicket
#

God organizing Unity code is hard, I've been mulling over how to do something for like an hour rofl

indigo arrow
#

I would only create 1 for the type of upgrade and then move on to the next upgrade

pure cliff
# indigo arrow ngl never seen StrategyManagers before

So chances are it looks like:

public class StrategyManager : IStrategyManager
{
   private Dictionary<StrategyType, IStrategy> Strategies { get; }
   public StrategyManager(List<IStrategy> strategies)
   {
      Strategies = strategies.ToDictionary(s => s.StrategyType, s => s);
   }

   public IStrategy Get(StrategyType strategy) => Strategies[strategy];
}
indigo arrow
#

upgrade a would only have 1 SO a, upgrade b only 1 SO b, etc etc

pure cliff
#

it should be typically quite simple and is, for all intents and purposes, usually just some variation of a readonly dictionary

indigo arrow
#

is Strategies a real thing or just a variable name

rocky basalt
#

Learn dictionaries asap PQ, they're super nice

pure cliff
#

In fact usually I make it literally just a ReadonlyDictionary<TheEnum, TheInterface>

indigo arrow
pure cliff
lucid valley
peak thicket
#

Dictionaries are incredible

indigo arrow
pure cliff
#

So based on this code here @indigo arrow : #archived-code-general message

Your interface would simply just be:

public interface IStrategy
{
   StrategyType StrategyType { get; }
   void DoSomeUniqueLogic();
   void DoSomeOtherUniqueLogic();
}
#

Then youd just implement all your versions of that, and just inject them into your StrategyManager (note how it takes in a List<IStrategy> in its constructor)

indigo arrow
#

From what I'm getting, dictionaries are just basically a pokedex in a sense no?

#

where each item in it has a name and a number assigned to it

pure cliff
#

They are a mapping of a Hashset Binary Search tree to a value

rocky basalt
#

just read some tutorials about it

indigo arrow
#

and then that item has its own things and variables

indigo arrow
rocky basalt
#

they're super fast

#

you can even use value tuples as dictionry entries

pure cliff
#

@indigo arrow does everything I wrote make sense or you got any questions?

indigo arrow
pure cliff
#

So you can only have 1 parent... but you can have as many or few jobs as you want, but the compiler will demand you fulfill all the things those "jobs" (interfaces) say you have to do

peak thicket
#

Think of abstract classes as like, a big picture of what a class is. For example, a Gremlin or a Goblin or a Dragon are all "Monsters", and all monsters share a ton of behaviours.
But for interfaces, think of them like individual behaviours. Like, CanFly, or CanStealth

#

Abstract classes are great because you can lump them all together in for example, a List of Monsters can contain some Goblins and some Dragons, etc. And you can treat them all the same

pure cliff
#

The big thing is an interface is a contractual obligation, but it also acts as a mask.

Your class may have 5 methods, but the interface only exposes 1 of em

#

But if you have something like

public interface IFruit
{
   void Eat();
}
public class Apple : IFruit
{
}

The compiler will yell at you and throw an error, because Apple doesnt have the Eat() method declared on it

indigo arrow
peak thicket
#

I haven't looked at your question yet, I can't say for sure

#

I'm knees deep in my own programming issue atm lol

indigo arrow
lean sail
indigo arrow
#

it was more of a general question

lean sail
#

you can have a list of IMonster if you were to declare that interface, vs a list of Monster if that were an abstract class

peak thicket
#

True, but abstract classes communicate better what this object "is" in the grand scheme of things

indigo arrow
lean sail
#

1 major thing is you cant inherit multiple classes, but can multiple interfaces

peak thicket
#

Admittedly I rarely use interfaces tbh

rocky basalt
#

i dont think we have enough context on your problem to give a great recommendation

#

but also sounds like you are overcomplicating things and focusing too much on 'things' like interfaces, abstract, inheritance etc. i think you need to design more simple solution. just my unsolicited 2 cents

pure cliff
#

Basically my rule of thumb typically is:

Services: Composition
Data: Inheritence

#

All my "does a" things are interface'd and utilize dependency injection

All my "is a" things use inheritence if needed

#

If you have ever tried to serialize something with a non empty constructor, you'll quickly figure out why you do this lol

peak thicket
#

Ok so for my code rn, I have a bunch of Prefabs (which are just arrows that will show on the board) that I want a unit to be able to generate as the player begins giving it it's commands for the turn. Right now, I have each unit manage it's own order, but eventually, I want a Manager class to process all the units orders at once.
My issue right now is: whats the best way for the Unit to get access to these arrow prefabs? I can just inject each one into each unit, but that feels like overkill. I guess I should let the Unit have access to it's own manager class to grab the prefabs as it needs them?

indigo arrow
rocky basalt
#

There are many ways to skin a cat in programming, you usually don't "need" any of these things to solve a problem. The way we talk about them we make it sound like they're shiny products to grab off a shelf to solve problems. But at the end of the day it's up to you

indigo arrow
#

where the pickups grant you some sort of stat boost or ability

peak thicket
#

I see the logic there

pure cliff
indigo arrow
#

I don't know if i'm being silly but I've been stuck on this issue for a couple days and I'm still not understanding what you mean. How does your way do what I want

pure cliff
# peak thicket Ok so for my code rn, I have a bunch of Prefabs (which are just arrows that will...

I have my services as the owners of the GameObjects.

So my pattern I follow is my MonoBehaviors only really have the following:

  1. "Glass Box" methods that just do a thing and if they mutate anything, they only mutate stuff that specific GameObject "owns" (its transform, its animator state, stuff like that)
  2. Exposed information about the GameObject (its transform, its current state, etc)

Then I have all these managed by the parent service that does all CRUD for those objects, and it keeps track of which ones currently exist and where/who they are.

pure cliff
peak thicket
#

All that they manage is their own Glass Box methods as you mentioned, but also all the logic for how the Commands are given to them (after coming from an InputManager) and how said commands are displayed

indigo arrow
pure cliff
peak thicket
#

Yeah basically

pure cliff
# peak thicket Yeah basically

Id still classify those as "glass box" methods, it doesnt manipulate the game state and whatnot, its purely visual which is pretty much what I consider to be the MonoBehaviors "domain"

#

so sounds like you are on the right track!

peak thicket
#

Hell yeah 😎

#

But my issue rn is how to grab all these prefabs

pure cliff
#

Basically if you can "see it" I consider that to be the "point" of the MBs, they are the "view" part of MVC so to say

peak thicket
#

Makes sense. The Manager will take care of moving all the units and doing damage/etc once the time comes

#

But I guess maybe each Unit should have a reference to it's Manager and grab the prefabs from there?

#

The thought of a Singleton library class crossed my mind but I've had my fun trying to work with those. Never again

normal mica
#

hey! i don't know why i have so much trouble with this every time - I come from a javascript background and when I try to work in Unity, I get frustrated by my inability to treat classes (classes, not instances) like data.

for example, if I have an abstract Enemy class with several implementations, how can I create spawn tables (basically just lists of enemy types) from which I can pick one at random to spawn? do I just absolutely need to create one prefab per enemy in addition to the class they already have, or are there other simpler ways?

rocky basalt
#

Could you pool the maximum amt of prefabs you'd ever need, then when a unit needs some, make a function that grabs whatever available arrow prefabs exist, and release them when done?

leaden ice
#

kind of like a class prototype in JS

#

not really sure the terminology because i hate JS

normal mica
#

prototypes are objects in js unfortunately!

leaden ice
#

you have to make an instance of the class to actually have an object in C#

normal mica
#

i'm well aware

#

i'm asking how to solve this design problem within that framework

#

since i can't apply my usual methods

leaden ice
#

I don't understand your usual methods

normal mica
#

my usual methods would be like - put all the classes in an array, pick one at random, then instantiate the selected one

#

which works in js because classes are data

leaden ice
#

And don't really see what the design problem is. If you want a list of enemy type objects, construct instances of that type and put them in a list for example

leaden ice
normal mica
#

i can't instantiate them first because they're monobehaviours

leaden ice
#

That's your problem

normal mica
#

which means they need an object to attach to

leaden ice
#

You're using Monobehaviour

#

Don't

#

You can also just make a list of prefabs

#

And reference those in the inspector

#

There are many ways

normal mica
#

yeah i mentioned that possibility but i really don't like it because it feels completely redundant

leaden ice
#

Then just go with the first way

#

That would be most Unityish way though

#

A list of prefabs or ScriptableObjects

normal mica
#

a list of scriptableobjects doesn't help me get monobehaviours into the scene, but i guess you're saying not to do that anyway

leaden ice
#

If you want Monobehaviours in the scene you'll be Instantiating prefabs most likely anyway

normal mica
#

i'll see how that works without relying on the object hierarchy i guess

#

yeah but like

#

the problem with the prefab thing is that sometimes i want just one prefab that i can attach a randomly selected component to, and duplicating that prefab once per possibility creates a lot of maintenance burden

#

because there's (afaik) no prefab inheritance

leaden ice
#

There's prefab inheritance

#

They're called prefab variants

normal mica
#

oh sick, i'll look into that as well then

#

and try it without monobehaviours i suppose

#

thanks for your help

pure cliff
#

Strategy just means the like, chunks of unique logic

indigo arrow
pure cliff
#

like instead of an abstract class that has the common logic, and the "children" classes having the unique logic, you have a service with the common logic, and the strategies have the unique logic

indigo arrow
#

ah alright

#

i understand now

#

and i'd group them using a list or a dictionary or what

grizzled needle
#

hello! I'm running into a very strange issue with an input buffer thing that i'm doing. after a bunch of testing, i found that for some reason when I do this

second.enumVar = EnumVar.None;```
this some how makes `first.EnumVar = EnumVar.None` even if `second.enumVar` was something different before. So it looks like it's treating it as a reference type, however this is an enum which should just be a value type. Does anyone know what's happening here?
somber nacelle
#

there's gotta be something other than just these two lines affecting one or both of those objects because enums are value types so they are copied not referenced

grizzled needle
#

the actual snippet that i'm looking at is this

#
                TransferQueuedInput(CurrentWeapon, swapWeapon);
                Debug.Log(swapWeapon.queueInput); // Returns PRIMARY FIRE input

                if(CurrentWeapon != null)
                    CurrentWeapon.gameObject.SetActive(false);
                Debug.Log(swapWeapon.queueInput); // Returns NONE input```
#

TransferQueuedInput() is simplified atm, so theres no problem there

#
        {
            if(from != null)
            {
                to.queueInput = from.queueInput; // FIX ME : REMOVE THIS
            }
            return;
}```
somber nacelle
grizzled needle
#
        {
            _state = WeaponState.IsPocketed;
            currentInput = WeaponInput.None;
            queueInput = WeaponInput.None;
            Ammo.ReplenishAll();
            _stateTime.Set(-1f);
            _primaryRecoverTime.Set(-1f);
            _alternateRecoverTime.Set(-1f);
            ResetBloom();
        }```
#

It does have that, but shouldn't on disable call after the transfer?

#

and it shouldn't effect the swapWeapon/first.enumVar?

somber nacelle
#

what does swapWeapon point to? because if it points to CurrentWeapon's component then of course that OnDisable is the issue

grizzled needle
#

okay, i see the problem!

#

so normally, swapWeapon should never point to CurrentWeapon, but because i'm doing some testing, it does actually point to the same gameobject in the scene

#

the fix should probably just be setting the enum after I enable the swapweapon

nova magnet
somber nacelle
#

you should for sure make those 7 repeated lines into a method that you can just pass the delay multiplier into. then yeah, you could create a switch statement just to get the multiplier to pass into the method

steady moat
#

SlidingState
AirState
GroundedState

haughty harbor
#

I don't see the "save scenes" as a selection

#

I was watching a video and they had "save scenes"

rigid island
#

its not save scene anymore

#

it's just Save

#

you see they have the same shortcut right and the editors versions are wildly different?

haughty harbor
haughty harbor
rocky basalt
#

I'm sure this is probably super easy, but could anyone recommend a best practice for procedurally rendering a kind of wireframe mesh, or constellation (see example image) ?

I'm currently using Line Renderer to draw lines between these points, but then I'm not able to scale it as if it's all one object.

I have access to all the points/vertices, and the list varies depending on gameplay (can be added and removed)

rigid island
rocky basalt
#

I'm doing this in code in runtime btw... Just wondering if I should do it via the Mesh class or other method

spring creek
haughty harbor
sick flint
#

Is there any way to make it so that an input field does not lose focus when clicking out of it

rigid island
sick flint
#

I have figured out a solution for this but is there a way to make it so that when the inputfield is focused it does not select all text?

#

I know the tmp just has a inspector thing for this but I have to use the old inputfield

sick flint
#

The way I have this set up works perfectly and I don't want to re code it, I know its lazy

rigid island
#

the text quality esp on the old Inputs fields is garbage lol

sick flint
#

wait I think I have it working

#

thank you for your help lmfao

#

I am using the tmp

rigid island
#

tmp is the way 👍

unreal trench
#

Hello. I am trying to make WASD top down movement, but the diagonal movement is clearly making my character look very buggy. When slowed down, he moves in the x first, and then really quickly after, in the y direction. This makes him look scrambled and jumpy. Any tips? Here is a vid including debug.log of 2d vector direction

#

my code for the player controlled ^. I have not edited any of the default InputSystem settings (the new input system)

torn eagle
#

Hey! Trying to create a game that will randomly select from a bunch of arrays with 100+ strings in them as the active string. What would be the best optimised way to do this? Parsing in csvs?

rigid island
#

sure

#

textfile would suffice too if they already separated you can use Split()

torn eagle
#

Oh sweet!

lean sail
torn eagle
#

Would it be as easy as selecting a random txt file on start and then assigning that as the array?

#

Sorry I'm a bit of a bozo when it comes to this lmaoo

rigid island
#

a scriptable object could probably work too

lean sail
#

you probably wouldnt want a bunch of text files all storing a few lines tbh, randomly choosing a file can be somewhat weird

rigid island
#

you could make it a text asset and put that inside an array

#

pick random index from array

#

parse the textasset

pure cliff
fathom plank
night harness
#

Having trouble with getting Handles.Label to display w/ OnGUI

[ExecuteAlways]
public class DetectionDebugView : MonoBehaviour
{
    public Detector detector;
    public Detectable detectable;
    public TextMeshProUGUI detectionRate;
    public TextMeshProUGUI tryModifyDetectionRate;

    void Start()
    {
        if (detector != null)
            detector.onModifiedDetectionRate.AddListener(TryModifyDetectionRateUI);
    }

    void Update()
    {
        if (detector != null && detectable != null)
        {
            detectionRate.transform.position = Vector3.Lerp(detector.transform.position, detectable.transform.position, 0.5f);
            if (detector.detectable == detectable)
            {
                Debug.DrawLine(detector.transform.position, detectable.transform.position, Color.green);
                detectionRate.text = detector.detectionRate.ToString() + "%";
            }
            else
            {
                detectionRate.text = "00%";
                Debug.DrawLine(detector.transform.position, detectable.transform.position, Color.red);
            }
        }
    }

    void TryModifyDetectionRateUI()
    {
        tryModifyDetectionRate.text = detector.tryModifyDetectionRate.ToString();
    }

    void OnGUI()
    {
        Handles.color = Color.white;
        Handles.Label(detectionRate.transform.position, tryModifyDetectionRate.text);
    }
}

my script right now, in theory only the bottom function should really matter. cant get the label to show at all

dusk apex
#

Log it's value before use (before the very line)

night harness
#

I can confirm that it’s not empty

dusk apex
#

So what did it print?

#

Should be visible in the console tab

fallow oar
#

https://hatebin.com/meeklhhwmy I am trying to load a add on the start of my level wich is running this script attatched to a gameobject. This should load it and then at the end of the level when the player clicks the retry or next button it send a event that should show the add. But its not working in the testing. Any suggestions?

night harness
dusk apex
lean sail
#

I believe that one might only be scene view

night harness
#

Scene view, all gizmos enabled

lean sail
#

can you try it with OnDrawGizmos

night harness
#

I don’t think so, as Handles.Lables can only be ran inside OnGUI?

#

Could be misunderstanding

lean sail
#

ah maybe im thinking of the wrong thing, ill test something quick

dusk apex
#

I've only ever used it in OnSceneGUI

lean sail
#

from the docs and other examples online, seems like everyone this as an editor script and OnSceneGUI

night harness
#

That’s why I was curious if it was exclusive to editor scripts or not

agile coral
dusk apex
#

Likely something wrong with your code.

#

No one really knows without seeing more.

agile coral
#

do you see how it is blue in the inspector?

#

like is there more than one thing I need to change to change the colour of a button?

#

button.GetComponent<Image>().color = Color.red;

prime sinew
agile coral
#

Solved. Idk why default material needs to exist, but the fact that I had changed it during previous attempts at changing button colour was the source of my issue

worn oasis
#

Hey guys, did the recent VScode update ruin the extensions for Unity for anyone else?

#

The 'Go to type definition' option is missing and the code is not color coded (when I install unity extension)

hidden parrot
#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

hidden parrot
#

Nevermind, the tutorial suggests an extension (which Ive never used and it worked fine)
Anyway, follow that

worn oasis
quartz folio
#

Check your C# and C# Dev Kit extensions are upgraded to the latest versions.

hidden parrot
worn oasis
#

@quartz folio @hidden parrot not sure whats going on, but the color codes are suddenly different

#

and I didnt do anything different

quartz folio
#

Microsoft has released a new version of the Unity extension for VS Code. The new extension relies on the C# Dev Kit. Did you do what I asked and checked you were on the latest versions of the extensions you have installed?

worn oasis
#

yes, I have

#

uninstalled everything and reinstalled them a few times too actually

quartz folio
#

Well, the VS Code extension is currently in a state of transition as a preview release, and was previously completely unsupported. I've advised people not use it in the past, and that isn't changing until they sort their shit out 😛

worn oasis
#

what do you suggest?

lean sail
#

visual studio/rider are the 2 real options

quartz folio
#

if you have access to JetBrains Rider (students can get it via the github student program) then I highly recommend it

worn oasis
#

I think the issue is that the old unity debugger had been deprecated and I'm now required to use the the new unity extension by microsoft

lean sail
#

well the real issue is that you're using vscode, and the extension is still a preview

worn oasis
#

I can't get jetbrains tho

#

I'll check rider

#

Oh wait, nvm they're one and the same

lean sail
dusk apex
#

Try the VS ide (non code)

worn oasis
#

ooh

dusk apex
#

VSCode is a text editor with extensions.

#

Similar names, different animals.

quartz folio
#

The debugger is built-in to the new extension afaik

#

you shouldn't have the old one installed

worn oasis
#

Alright, I'm downloading vs ide now, let you guys know how it goes, appreciate the help

wintry crescent
#

If I enter playmode or make a build, are all OnValidates called? Or do I need to view everything in the inspector

#

On every object

hidden parrot
#

What are you using OnValidate for that requires a build?

sacred frost
#

but yeah it does not work in build

hidden parrot
wintry crescent
#

In onvalidate I make sure that some references are always to correct objects, which would change if I copy them to a different point in hierarchy
But it's super useful for me to just copy those objects around, and I keep forgetting to update the references

#

So in OnValidate I find the proper references and update them

royal temple
#

Hello, I Instantiate a gameobject using Instantiate(myPrefab); from a Script that is attached to a gameobject in the scene DontDestroyOnLoad.
For some reason, right after (same frame, or frame after), it is immediately destroyed by Unity with 0 callstack given to me (it's called from Runtime.dll).
Has anyone ever faced this issue? What are the common causes? I'm out of ideas... Thank you

worn oasis
#

The 'Go to type definition' option is also missing in the vs ide 🤔

wintry crescent
#

Or does it happen always when spawning that object

onyx badger
#

how to untag object from script?

royal temple
#

It seems to be happening only in this specific situation, I've spawned other objects without trouble in other circumstances

royal temple
royal temple
# wintry crescent Or does it happen always when spawning that object

Although that's a good point, maybe I should try spawning that same object from elsewhere. But to be fair, I've had the issue with 2 different gameobjects, spawned from the same place in code. So I was assuming the issue was with the actual spawning, not with what was being spawned

wintry crescent
royal temple
#

I will try to do so, will let you know, thank you

royal temple
#

I have managed to successfuly spawn that same gameobject from a script in another object in the current scene and attach it to a Bone on the character

#

One thing interesting to mention though, is that I've logged the Scene of said gameobject and it shows properly "DontDestroyOnLoad" so the spawn itself works

#

But it gets garbaged by Unity with no warning....

royal temple
# onyx badger ok

Setting it to null seems to trigger a Unity warning. Maybe setting it to "Untagged" would work

gloomy stirrup
#

hello .... I added a button and it just simply doesnt work... idk why , didnt even added a script

#

I mean its not fading in

royal temple
gloomy stirrup
#

wait i will re rec it

royal temple
wintry crescent
royal temple
#

You think it could be conflicting with each other?
You're right in saying that attaching it to an object in DontDestroyOnLoad is already adding it to that scene. The reason I did both was because I tried everything successively, but code is redondant, indeed

gloomy stirrup
wintry crescent
meager wasp
#

Hi, I have a. .gpx file that I want to use the data from in unity. I found different thing online for xml but haven't found anything for gpx. Can anyone point me towards how to do it? Using the XML class gives me (XmlException: Data at the root level is invalid. Line 1 position 1)

wintry crescent
royal temple
royal temple
wintry crescent
royal temple
simple saffron
#

If you have a list/array of an abstract class and add child classes to that list, will the inspector show the correct fields, or only fields included in the abstract class?

royal temple
#

And my character is in DontDestroyOnLoad

wintry crescent
#

so in this way, a non-DontDestroyOnLoad object would spawn it, but it'd still be controlled by your DontDestroyOnLoad object

#

you might have to try and get more fancy if you've got many characters that need it

#

but it's doable

royal temple
#

Not sure I understand your first sentence

#

My script is already essentially attached to my character (which is inside DontDestroyOnLoad)

lean sail
#

Does your character have to be DDOL in the first place?

wintry crescent
#

were you marking the new object as DontDestroyOnLoad when you were spawning it?

royal temple
royal temple
#

Right now, spawning it using: _heldItem = Instantiate(i.Prefab, Vector3.zero, Quaternion.identity, m_ItemBone); is also destroying it

#

This line is called from a script inside DontDestroyOnLoad

#

But it feels like it's a Scene like any other, so why wouldn't I be able to spawn something from there...

#

I have to get going somewhere, sorry for running off in the middle of you trying to help me. I appreciate the help 👍

wintry crescent
royal temple
#

I was doing it that way before, does not work either

#

Oh nevermind I wasn't attaching it to parent

#

I will try when I'm back on computer

#

Why parent and not transform?

#

There is an object holding that script above so if your intention was to have me try to put it in the DDoL scene that way, I will have to do parent.parent

wintry crescent
wintry crescent
wintry crescent
# wintry crescent which unity version are you using? I made a test script, and everything seems to...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DontDestroyOnLoadTest : MonoBehaviour
{
    [SerializeField]
    private GameObject _prefab;
    private IEnumerator Start()
    {
        DontDestroyOnLoad(gameObject);
        yield return new WaitForSeconds(1);
        Instantiate(_prefab).name = "Prefab1";
        yield return new WaitForSeconds(1);
        var prefab2 = Instantiate(_prefab);
        prefab2.name = "Prefab2";
        DontDestroyOnLoad(prefab2);
        yield return new WaitForSeconds(1);
        var prefab3 = Instantiate(_prefab);
        prefab3.name = "Prefab3";
        DontDestroyOnLoad(prefab3);
        prefab3.transform.SetParent(transform);
    }
}

that's the test script

neon pagoda
#

I guys, i don't know if this is the right place, but i didn't find a specific Windows platform channel.
On an application (target Win10/Win11) developed with Unity 2022.3.* and il2cpp as a scripting backend, on the resulted build we obtain a malware false positive from Windows Defender (we are sure that the build machine is not infected). Anyone has had experience with issue like that and has some hints to solve?

Thanks in advance

royal temple
wintry crescent
royal temple
#

Interesting that your code uses the Start function but changes the return type. Unity calls those function by string? That's wild

quartz folio
#

Start can be a coroutine, but nothing else

royal temple
#

Oh i see, thanks

royal temple
#

I've attached it to a random gameobject in my scene, it got moved to DDoL and instantiated everything. All 3 are present

wintry crescent
#

just make backup copies before you do so :P

royal temple
#

Yes, I'll keep digging, but it is indeed pretty weird

wintry crescent
#

so you don't have to recreate the objects later

royal temple
#

Oh yeah no worries, it's a prefab and I have versionning x)

#

Fairly new to using Unity again, but I'm not a beginner programmer :p Thank you for all your help and advice, appreciated

olive karma
#

!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.

olive karma
rustic nymph
#

hello, im struggling to create a lock on system with cinemachine. i found one tutorial that uses state driven camera but im already using one with my player as the animated target for the camera cinematics in combat. is there anyone knows other tutorial vids for cinemachine or maybe could help me.

#

or is it possible to use 2 different state driven cams?

main shuttle
# olive karma does somebody know why?

The only thing you do as far as I can see is (I don't see anything related to animation > play):

            float dot = Vector3.Dot(doorTransformDirection, playerTransformDirection);
            anim.SetFloat("dot", dot);

So probably from ClosedIdle the 2 outwards arrows transitions do something with the "dot" info which you are not showing, which probably has the problem in it.

main shuttle
#

And the other one too please

olive karma
#

what arrow?

main shuttle
olive karma
#

the one pointing from openOut to closedFromOut?

#

oh ok

main shuttle
#

Seems good to me

olive karma
#

yea

#

I cant figure it out too

main shuttle
#

So debug.log the dot product.

olive karma
#

I dont think I debug.logged it correctly

#

what line do I need to add

#

I just added Debug.Log("dot")

main shuttle
#

remove the quotes

#

And then open it straight in front of the door, and then straight back of the door.

olive karma
main shuttle
#

So yeah, that's not correct.
Try this, in my head this should work:

            Vector3 doorTransformDirection = transform.forward;
            Vector3 playerTransformDirection = (FirstPersonController.instance.transform.position - transform.position).normalized;
            float dot = Vector3.Dot(doorTransformDirection, playerTransformDirection);

            anim.SetFloat("dot", dot);
            anim.SetBool("isOpen", isOpen);
olive karma
#

nope still opens the same way

main shuttle
#

Still the same debugs too?

olive karma
#

no there are other debugs tho

#

let me screenshot them

#

its gonna be some really obvious mistake

main shuttle
#

FirstPersonController.instance.transform.position probably this then

olive karma
#

yea but I made the public static FirstPersonController instance;

#

in FirstPersonController.cs

#

on line 140

#

and in Awake I wrote instance = this;

#

not the best way of doing it

#

but it should work

#

last time I was coding sounds into the game and I was debugging why I dont hear them and it was because the window was muted

#

it has to be something like that

main shuttle
#

Can you debug.log FirstPersonController.instance.transform.position too on all 3 dot debugs?

olive karma
#

sure

#

1st back open, back close, front open

main shuttle
#

So Debug.Log($"DOT: {dot} FPC {FirstPersonController.instance.transform.position} DoorPosition {transform.position}); should work.

#

I think the problem is the door then

#

The pivot of the door is not in the place you think it is.

olive karma
#

?

#

I set it in blender on the edge

#

that should be the pivot

main shuttle
#

We will see 🙂

olive karma
#

if it helps my problem

main shuttle
#

So your blue arrow points upwards

#

And you are always on the floor

olive karma
#

what does that exactly mean?

main shuttle
#

So you are always at the back of the door

olive karma
#

oh

#

what did I do wrong

#

I downloaded blender 1st time in my life today

#

maybe thats why

main shuttle
#

You can probably instead of Vector3 doorTransformDirection = transform.forward; do Vector3 doorTransformDirection = transform.up;

#

As a temp fix

olive karma
#

yea kinda works but in the other direction

#

so basically Im facing north and the door opens south

#

and the other way around

main shuttle
#

Yeah you can flip it if you want

#

Anyhow, fixing the model is the way to go

olive karma
main shuttle
#

In Unity 3D, the blue arrow is always the forward of an object

olive karma
#

I had no idea

#

ty for that information

main shuttle
#

Not a problem, now you know 🙂

olive karma
#

do you have an idea of how to fix it?

main shuttle
#

Its a whole mess to be honest, most game engines have their own system of what is up and down, left and right and forwards and backwards

#

Yeah, Blender should have a way to export to Unity afaik

olive karma
#

does anybody know how to apply rotation and scale in blender?

main shuttle
olive karma
#

so i know what the problem is now

#

but I dont know how to fix it

#

look closely

jade kindle
#

Hey, I can't see Dynamic Parameters on the inspector for UnityEvents

rigid island
#

did you create a method with compatible param

rigid island
olive karma
rigid island
olive karma
#

cuz I would need to fix the model

#

and I hate blender

jade kindle
#

` public class CarCustomizationManager : MonoSingleton<CarCustomizationManager>
{
public UnityEvent<CarPartCategoryUi> selectCarPartCategoryUi = new();

    public void SelectCarPartCategoryUi(CarPartCategoryUi carPartCategoryUi)
    {
        switch (carPartCategoryUi.toggle.isOn)
        {
            case true:
                CameraManager.instance.SwitchCamera(carPartCategoryUi.freeCamera);
                break;
            default:
                CameraManager.instance.SwitchCamera(carPartCategoryUi.selectionCamera);
                break;
        }
    }
}`

Here is the class and the method I want to invoke.

rigid island
rigid island
olive karma
#

btw ty to everyone whos been helping me

jade kindle
jade kindle
leaden ice
rigid island
#

oh its a custom class

leaden ice
#

UnityEvent only supports simple parameters

jade kindle
#

And CityComponent is a Monobehaviour

rigid island
#

thought was enum lol the switch threw me off but realized it's in toggle

#

i guess enum would work then but you're using custom class, big no no in inspector

jade kindle
leaden ice
#

Either primitives like numbers, bools, strings or UnityEngine.Object

rigid island
#

use delegate or Action and do it via code to pass objects @jade kindle

jade kindle
rigid island
#

cause a class is not a dynamic parameter

leaden ice
jade kindle
#

So the inspector is mostly useless

#

like unity itself

rigid island
#

being inspector bound is limiting and also very confusing to find things

jade kindle
leaden ice
rigid island
#

id love to see what u come up with instead lol

jade kindle
swift falcon
#

What are some good challenges for intermediates?

leaden ice
swift falcon
#

I just got a pixel and they are already brainwashing me

leaden ice
swift falcon
#

Alright, thanks guys

fervent furnace
#

the first question can be modified as: return the sum of two number...without using any arithmetic operator....

primal needle
#

Hello. I have a unity game that I export as WebGl. Right now, it just has a script that run when a user clicks a button and it loads a OBJ model and JPG file for the texture. Both files are on a server. the obj file loads fine, but the jpg file causes this error in the browser: Build.framework.js:3 DirectoryNotFoundException: Could not find a part of the path "/https:/localhost:7191/FileServer/IMG_1.jpg". at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) The code I have is: ```
Renderer rend = model.transform.GetChild(0).GetComponent<Renderer>();
byte[] fileData;
fileData = File.ReadAllBytes("https://localhost:7191/FileServer/IMG_1.jpg"");
Texture2D tex = new Texture2D(2, 2);
tex.LoadImage(fileData);

patent tartan
#

Should I learn c# before learning unoty

modern creek
modern creek
patent tartan
#

K

patent tartan
modern creek
#

🤷‍♂️

#

I haven't watched that video, and I'm certainly not a CS/C# teacher - there's probably some googleable resources for that. "How can I learn c#" or "What's the best way to learn c#"

primal needle
wide dock
#

But yeah, a 9h video isn't that long and should keep you interested, so it's a better start than none

modern creek
#

There's no built in functionality in Texture2d.LoadImage to do that

primal needle
#

I'm going to see if something like this works: ```
WebClient client = new WebClient();
byte[] fileData = client.DownloadData("https://example.com/file.txt");

peak thicket
#

Is there a way to let a library class have access to specific prefabs? I want it to return them based on the result of a static method call

modern creek
peak thicket
#

Right now the class in question is static

modern creek
#

That's fine..?

peak thicket
#

Can you inject stuff into static classes?

modern creek
#

inject isn't the right word.. pass as a parameter

#

there's no reason you can't do:

public static class MyStaticClass{
  public static MonoBehaviour SomeMethod(MonoBehaviour thing) { /* modify thing and return it */ }
}
peak thicket
#

Oh no not like that, I mean the static class "dispenses" the prefabs

wide dock
peak thicket
#
public static class AdjacencyHelper {
    public static GameObject getConnection(Pair<int, int> source, Pair<int, int> dest) {
...
}
modern creek
#

As far as architecting it is concerned, I'd probably make static methods in the prefab you're interested in.. without knowing too much more about what you're trying to do, it seems like the prefab itself should know whatever "getConnection" is? Either you create it and tell it what it's connection is, or it can find it on it's own? Am I making sense..?

peak thicket
#

Kinda, but these prefabs don't have any logic, they're just visual components that I'll create and destroy

pure cliff
# peak thicket Can you inject stuff into static classes?

No, big reason why I avoid using them.

I would start getting familiar with dependency injection personally, but if you really wanna use the static class, I would make a MonoBehavior that you put all the prefab refs on and then on awake the monobehavior "loads" all those prefabs into your static class

peak thicket
#

each unit has a class that manages these arrows (arrows are the prefabs)

peak thicket
#

Totally doable, but I'm just looking into alternatives atm

#

Totally fair to avoid loading any logic into static classes though, I've tried working with singletons before. Pain.

winged karma
#

Hey all, I have a small inquiry regarding the use of Find(), FindGameObjectsByTag() etc.

I know they generally run heavy and I often try to find other workarounds such as having static variables that objects assign themselves to at runtime, but I was wondering - is there a way to delay other functions until the Find() function has fully executed? For instance, putting it in a coroutine and triggering an event once it has finished so nothing else runs until it has completed its function?

pure cliff
#

So my approach I have been using is as such:

  1. All my monobehaviors inherit from EntityBase (which inherits from MB), that has my core "all entities have this logic" on em. Primarily it exposes position, destroy, animator state, and a Guid I assign to the object

  2. I have all my "pre-existing" entities registered to my dependency injection system on Startup, the DI registration is a MB so I can just drag and drop refs to it, and then it caches em all on startup

  3. I have my EntityService which tracks every entity (by type), loading in all the ones cached in step 2, and then all my CRUD for every entity passes through EntityService so it implicitly knows whenever an entity is created or deleted and it tracks those refs.

  4. I have a set of static Guids in a static class that I assign to, for specifically assigning constant Ids to singleton entities that are important and I need to fetch often (for example the Player has the same Id every time always)

#

Interestingly, this is an answer to both @peak thicket and @winged karma

peak thicket
#

Interesting...

#

I'll read over this a bit

bleak abyss
#

can anyone suggest a book for unity game development?

modern creek
bleak abyss
#

I am trying unity learn pathway to learn right now
any suggestions?

modern creek
#

Lots and lots and lots of youtube videos (YMMV for which you like, although I got started w/ Brackeyes years ago). Unity also has a lot of free resources on their portal. I think it's called Unity Learn?

bleak abyss
#

I am learning through Unity Learn
What do you suggest?

modern creek
modern creek
# bleak abyss I am learning through Unity Learn What do you suggest?

If you're already deep into unity learn, great. Start by making a game. Make pong. When you have a task you can't do, try to do it. 🙂

Unity (and development in general) is about breaking the problem down into smaller and smaller components until the tiniest possible component or line of code is doable.

#

Repeat that process a few million times, and you'll have a game

modern creek
#

(Find other people's open source libraries if you can and look through them - game jams are a great place to start)

#

GMTK just hosted a huge game jam (20k+ entrants). Go through them, find entrants that posted their source code and see if you can figure out how they made their game work.

winged karma
# modern creek Find() and all the others aren't threaded, so there's no need to "delay other fu...

Well, just as an example, I've been continuing development on an old turn-based RPG jam project on my PC and when switching to combat the game was using FindGameObjectsWithTag() to compile a list of existing active encounters. It worked fine on my PC but I realized when running it on my laptop it never managed to grab the objects before switching scenes, so I changed tactics. It's possible it was something else but having encounters add themselves to a static list instead seemed to fix it.

modern creek
#

So what I'd do for that instead of maintain a list of encounters in a singleton and make that singleton DontDestroyOnLoad (DDOL) so it just sticks around between scenes or whatever

#

That's my pattern of choice and I love it

#

So, trivialized example, but here we have GameManager - it doesn't yet have any static public methods, but you get the point.. I can access it from anywhere without worrying about refinding objects that I care about

winged karma
#

Pretty much where I was headed - I was just curious whether having Find-likes trigger an event upon completion was viable at all

modern creek
#

you could do that, but that sounds incredibly messy

#

(like, pub/sub isn't really the best application for that pattern, imho)

winged karma
#

Fair enough! So better to not use it then

pure cliff
#

The next "step" in terms of this pattern is getting away from these singletons is to instead start using a DI engine like Zenject or whatnot to register POCO singletons, which removes your need to do the whole FindObjectOfType style calls, and instead you just use the class "as is" and a tonne of overhead effort gets removed, replaced instead with just needing to make sure you register stuff on your DI Container

winged karma
#

Thank you @modern creek and @pure cliff

pure cliff
#

@winged karma @peak thicket heres an example of what my POCO Service looks like, note how it is decoupled away from needing to be any kind of MB / SO, and is just a plain ole class, and it has no static methods on it. We constructor DI the "pre-existing" refs from the scene so we can track/watch em, and then away we go

https://hatebin.com/oltjqjncse

#

This makes testing and whatnot a lot easier as I can just mock a fake implementation of IEntityService if needed to return "fake" entities and whatnot

winged karma
#

Neat! Thanks for sharing

#

I'll keep that in mind for future projects

forest wharf
#

I've got something I can't figure out; I have a timer ticking each frame (implemented as a variable with Time.deltaTime subtracted from it), yet the interval seems to be subtly wrong. This is the log output from a test case for a timer that's supposed to tick at 2Hz for 3 seconds:

MetronomeTicksAtSpecifiedFrequency(2Hz,3) (3.347s)
---
0.5
0.4630973s, 0 beats, 0s remaining in timer # Shouldn't tick until 0.5s
0.9637057s, 1 beats, 0s remaining in timer # Shouldn't tick until 1.0s
1.466129s, 2 beats, 0s remaining in timer # Shouldn't tick until 1.5s
1.966367s, 3 beats, 0s remaining in timer # Shouldn't tick until 2.0s
2.470103s, 4 beats, 0s remaining in timer # Shouldn't tick until 2.5s
2.973784s, 5 beats, 0s remaining in timer # Shouldn't tick until 3.0s

Any idea why this might be happening?

wind palm
forest wharf
#

The comments list when the timers should tick. I know that I'm not going to be able to hit exactly 1.0 seconds or 1.5 seconds or 2.5 seconds. I just want to ensure that the timer doesn't go off until that length of time has passed.

wind palm
stark sinew
#

If I understand your problem correctly, it's ticking ~0,03-0,04 seconds too early?

Where are you doing the tick? Inside Update or somewhere else?

forest wharf
# wind palm What's the code you're currently using?

This is my test case

        [UnityTest]
        public IEnumerator MetronomeTicksAtSpecifiedFrequency([ValueSource(nameof(Frequencies))] Frequency frequency, [Values(1, 2, 3)] int duration)
        {
            Assume.That(_time.TimeScale, Is.EqualTo(1.0f));
            var beats = 0;
            var elapsed = 0.0f;
            var metronome = _timer.CreateMetronome(frequency);

            Debug.Log(frequency.Period.TotalSeconds);
            metronome.OnComponentAdded += (e, _, component) =>
            {
                if (component is TimerExpiredComponent)
                {
                    Debug.Log($"{elapsed}s, {beats} beats, {(e as TimerEntity).Timer.remaining}s remaining in timer");
                    beats++;
                }
            };

            for (; elapsed < duration; elapsed += _time.DeltaTime)
            {
                yield return _ticker.Tick(); // Runs all systems once (equivalent to a frame)
            }

            Assert.That(beats, Is.EqualTo(frequency.AsPrimitive() * duration));
        }
#

And this is the code that ticks the timers each frame:

using System;
using CorundumGames.Services.TimeService;
using JCMG.EntitasRedux;
using JetBrains.Annotations;
using UnityEngine.Pool;
using VContainer;

namespace CorundumGames.Chromavaders.Systems.Timer
{
    internal sealed class TimerSystem : IUpdateSystem
    {
        [NotNull]
        private readonly IGroup<TimerEntity> _runningTimers;
        private readonly ITimeService _timeService;

        [Inject]
        public TimerSystem(TimerContext timer, ITimeService timeService)
        {
            _timeService = timeService ?? throw new ArgumentNullException(nameof(timeService));

            if (timer == null)
            {
                throw new ArgumentNullException(nameof(timer));
            }

            _runningTimers = timer.GetGroup(
                TimerMatcher.AllOf(
                        TimerMatcher.Timer,
                        TimerMatcher.TimerActive
                    )
                    .NoneOf(
                        TimerMatcher.TimerExpired,
                        TimerMatcher.TimerPaused
                    )
            );
        }

        void IUpdateSystem.Update()
        {
            var delta = _timeService.DeltaTime;

            using var scope = ListPool<TimerEntity>.Get(out var buffer);
            foreach (var e in _runningTimers.GetEntities(buffer))
            { // For each running timer...
                var timerDelta = delta * (e.HasTimerScale ? e.TimerScale.scale : 1.0);
                var timeRemaining = Math.Max(e.Timer.remaining - timerDelta, 0.0);
                // Ensure that the time remaining doesn't go beyond zero
                e.ReplaceTimer(timeRemaining);
                if (timeRemaining <= 0.0)
                {
                    e.IsTimerExpired = true;
                }
            }
        }
    }
}
forest wharf
stark sinew
#

I'll be honest, I've never used a DI and/or Entity Framework yet, so I'm not a big help.

What happens if you yield return null instead of yield _ticker.Tick() in your Test?

Are you sure that the issue is actually caused by the TimerSystem and not caused by your Test?

Do you actually use HasTimerScale and if yes, may it be related?

What if you use Clamp in some way instead of Max to prevent the timer from going beyond zero?

forest wharf
stark sinew
#

If it's always 0,03-0,04 seconds early, could this mean that it's kinda skipping one frame?

In your Test, what happens if you use elapsed <= duration instead of elapsed < duration?

I'm just making wild guesses, sorry

forest wharf
#

Let's find out

#

That's okay, wild guesses can be helpful if they lead me in the right direction.

#

Although elapsed is a double, so it'll probably never actually be equal to duration (which is an int). So I'm not expecting any different behavior here

#

Yeah, same behavior

#

Although...you said something about skipping a frame. In my timer code, the IsTimerExpired message is sent as soon as the timer is expired, rather than at the end of the frame. (The TimerSystem runs at roughly the start of the Update phase.)

stark sinew
# forest wharf Although...you said something about skipping a frame. In my timer code, the `IsT...

Ok, that's kinda helpful!

iirc, your timers run one after another inside a loop, including the IsTimerExpired = true, correct?

Could you, instead of setting that flag while looping over the timers, kinda cache the timers that are done and set their flags in another loop that runs at the end of the function?

Idk if it's clear what I'm trying to say

something like

LOOP 1
foreach timer
- update the timer
- if timer is expired, add timer to a collection

LOOP 2
foreach timer in that collection
- set the IsTimerExpired flag to true (and call ReplaceTimer?!)

Basically, what I'm trying to say, maybe it's behaving differently if you set IsTimerExpired (and/or the ReplaceTimer) in its own loop after the actual calculations are done, I'm assuming that one of both is firing an event on call/change and those may be slightly out of sync because of the calculations you're doing before

We need some of those Unity Discord legends here, pretty sure they would've solved it already 🤣

forest wharf
#

How so?

solemn raven
#

hi , is it possible to add two materials on top of eachother for the same mesh ?
for example, is it possible to make a sphere with a red material then add another material for like a transparent magic effect on top of it of it without having to add another sphere mesh ???

leaden ice
#

both will be used

solemn raven
leaden ice
#

i don't understand that

#

obviously one of them will need to be transparent or cutout if that's what you're asking

solemn raven
forest wharf
# stark sinew Ok, that's kinda helpful! iirc, your timers run one after another inside a loop...

iirc, your timers run one after another inside a loop, including the IsTimerExpired = true, correct?
Yes. All timers are ticked down in sequence, although they all get the same Time.deltaTime value.

Could you, instead of setting that flag while looping over the timers, kinda cache the timers that are done and set their flags in another loop that runs at the end of the function?
Yes, I could, but...

I'm assuming that one of both is firing an event on call/change and those may be slightly out of sync because of the calculations you're doing before

...in my test case, this is the only timer so it would make no difference. And in my actual game logic, event handlers aren't used like this; the entities that listen for certain kinds of expired timers (as determined by components that aren't shown here) react when their own systems are executed later in the frame.

stark sinew
solemn raven
stark sinew
jovial moon
#
[CreateAssetMenu()]
[Serializable]
public class BaseStats : SerializedScriptableObject
{
    [SerializeField]
    public Dictionary<Stat, double> stats { get; private set; }
}

I have this class. When I make an Asset from it and add an item into the Dictionary, it does not persist a Unity restart. How could I fix this? :c

leaden ice
stark sinew
stark sinew
forest wharf
jovial moon
#

Is there an alternative where I can make this work? I am using Odin here

stark sinew
solemn raven
#

i can see a mix between both colors controlled by alpha
but it also said this warrning

leaden ice
#

that last one is best I think because relying on odin serializer isn't a great move

stark sinew
# jovial moon Interesting... Thank you!

It definitely has a big disadvantage, you can't cheat with a generic KeyValuePair<X, Y>, you'll need to have classes with explicit Types assigned to them, it's not scaling well but it may be enough for simple things

Imagine the need of having classes like KeyValuePair_Float_String, KeyValuePair_String_GameObject etc

jovial moon
#

Yes I am not happy with that solution at all, but it is interesting to know this... Mmm...

#

Omg SerializedDictionary exists

#

AND IT WORKS

stark sinew
# solemn raven it actually worked ,i have just tried it

Oh damn, shame on me, interesting!
But you should take that warning seriously, that's not the preferred way to do this I think.
If your project uses URP or HDRP, you should try to create a shader with ShaderGraph, it's really easy even for beginners!

leaden ice
#

it just serializes as a list of key/value pairs

steep saddle
#

Is is possible (and if so, advisable) to change the game object icons in the hierarchy?

cold parrot
# steep saddle Is is possible (and if so, advisable) to change the game object icons in the hie...

It’ll make working with prefabs more annoying. If you need a better hierarchy view use something like https://github.com/WooshiiDev/HierarchyDecorator

GitHub

Lightweight Unity Plugin transforming the Hierarchy into what it should be. Adds headers, styles, icons and more. - GitHub - WooshiiDev/HierarchyDecorator: Lightweight Unity Plugin transforming the...

steep saddle
cold parrot
#

You won’t see the icon anymore so can’t differentiate prefab from regular object

wintry crescent
#

Is there a way to forcibly serialize a hashset?

#

Or something like that

#

I don't like to bother myself all the time with recreating it whenever the object is created or a list changes

#

or at least something with the functionality of a hashset

#

I like O(1) lookups

unreal valley
#

Is there any way to set an Animation Curve to a Preset in code?

somber nacelle
#

wdym by set it to a preset? if you mean like create a default Constant, Linear, or EaseInOut curve there are static methods on the AnimationCurve class to do so

unreal valley
#

So I have created one in the Editor. Was wondering if there was an easy way to pick that out.

somber nacelle
#

probably with some editor code, but that's not something you'd be able to do at runtime. unless you did something like stored those curves on a scriptable object or whatever and assigned it from that SO

unreal valley
#

That's what i figured. I suppose ill go that route than. Thank you

timid meteor
#

hit.transform.gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero; this may be a really fast answer but is there a way to instead of completely stopping the bullet it goes to a really low amount?

#

like .1 or .5 speed

somber nacelle
#

normalize the velocity and multiply that by your desired speed

leaden ice
timid meteor
#

ah ok ty

somber nacelle
#

also if that hit is a RaycastHit or RaycastHit2D you don't need to getcomponent for the rigidbody, it has a rigidbody property

leaden ice
#

good point

timid meteor
#

it's also working with vr hands that I have

#

Thanks for your help though 😄

rustic furnace
#

Hello all, I am having trouble with spawning a prefab and making it move from the player to the mouse position. I have tried to find the problem via debugging and checking if I had the right tags, changing values, but nothing worked. The projectile is not moving from the player to the mouse position and I have no idea why. I'm trying to make a simple game, where I can move the player using right mouse button and shoot a projectile with left mouse button, both going towards the mouse location input. I got the player moving done but moving the projectile is giving me trouble.

Instantiating the projectile via player script: https://gdl.space/ugeroninoq.cpp
Moving the projectile to mouse position: https://gdl.space/ezeboveher.cpp

#

Also, the projectile, once instantiated, just stays at the player position and doesn't go to the mouse position for some reason, even tho the movement of it is in update(), it also jitters weirdly

somber nacelle
#

by "not working" do you mean it instantly appears at the mouse position instead of moving from the player to the mouse position?

rustic furnace
#

yeah

somber nacelle
#

that's because you are moving it 1000 units per second

rustic furnace
#

oh

#

I reduced it to 10

#

now it's staying at the player position tho

somber nacelle
#

also you should be moving it from its current position to the target position

rustic furnace
#

Okay I just did that and it worked

#

why

#

player.transform.pos should be the same no?

#

since it got instantiated at that position

somber nacelle
#

that's the starting position. but not where it currently is. if you were lerping, i'd say use that yes. but you're not. also if the player moves during this the direction suddenly changes

leaden ice
#

That line is definitely wrong

rustic furnace
somber nacelle
#

no you were just doing it wrong. look up Vector3.MoveTowards to see how it works

humble kraken
#

<@&502884371011731486> i need to tell you something

humble kraken
#

chat gpt told me something i never know it about moderators

vagrant blade
#

I'll stop you now and tell you if you shitpost, you will be muted. So decide how you want to proceed.

humble kraken
#

what is shitpost

#

i dont know anything about discord i joined on June 2

#

I think i know shitposting

#

its summoning a moderator for nothing

jaunty sleet
#

U shouldn't @ mods for no reason lol

#

Also does anyone know what happens if you call StopAllCoroutines() from inside a coroutine? The coroutine that called it will continue right?

humble kraken
#

please i am respectiful i am following the rules right

simple egret
jaunty sleet
#

Ok, so it does stop itself then. Do all coroutines go until the next yield when you stop them?

simple egret
#

Yeah, in a coroutine everything runs at once until you hit a yield. That's why you freeze Unity if you have a loop with no yield in it

#

It runs until a yield, but there isn't any, so it continues forever

jaunty sleet
#

The order of updates always gets me when I'm working on complicated stuff with coroutines lol

steep saddle
#

How can I pass an array so that the receiving function cannot change the original? Do I just need to make a copy before passing it?

late lion
#

Otherwise, you will either have to make a copy or use a wrapper object like ReadOnlyCollection<T>.

pure cliff
#

If the array never needs to mutate at all you can even store it in a readonly span from the start, to reduce costs

steep saddle
#

It will need to change, but I just want to restrict the receiver from doing so.

steep saddle
pure cliff
steep saddle
#

...disregard, I misunderstood something.

lean sail
hidden gulch
#

how do i make my navmeshagent turn faster?
when i move the target location to behind it it takes too long to turn and start going in the direction of the target location

wintry crescent
#

If I'm in prefab view, and I call FindObjectsOfType, why does it find only scene objects on the previous scene, not objects in the prefab I'm currently viewing? it makes no sense

#

I am in a scene MyScene. There are ManagedInteractionOutlines in the scene. I double-click a prefab from the project window, to edit it. In the prefab, I have a script with this function:

[NaughtyAttributes.Button]
    public void RefreshOutlineList()
    {
        if (_outlineList == null)
        {
            _outlineList = new List<ManagedInteractionOutline>();
        }
        else
        {
            _outlineList.Clear();
        }
        _outlineList.AddRange(FindObjectsOfType<ManagedInteractionOutline>());
    }```
when I run this script, _outlineList ends up containing all the ManagedInteractionOutlines that are present in the scene MyScene (which results in all objects displaying as Scene Mismatch) instead of containing all the ManagedInteractionOutlines that are present in the hierarchy of the prefab
#

can someone help me out? How can I do it properly, and grab those objects from the prefab?

#

Unity 2021.3.20

#

If I open it when viewing a different scene, for example one with no ManagedInteractionOutlines it just ends up empty, despite there being many shown in the hierarchy of the prefab.
The prefab doesn't even exist in the scene!!

vast wyvern
#

Hello !

Checking to see if anyone has had experience in converting HEIC photo files to different formats?

rigid island
vast wyvern
#

Sorry, I had more to type but got distracted. I was trying to accomplish this by passing photo bytes over to a texture2d

#

and then encoding that to JPG or PNG, but it seems to not like that. Wasnt sure if I was missing something in how I was handling that data or if there was reference to what format is support by texture2d and the ImageConversion class

rigid island
vast wyvern
#

Sure 🙂

    {
        if (checkAndObtainGalleryPermissions() == true)
        {
            minikinImageBytes = null;

            NativeGallery.GetImageFromGallery((path) =>
            {
                if (path != null)
                {
                    var tex = NativeGallery.LoadImageAtPath(path, -1, false);

                    var textByte = tex.EncodeToJPG();

                    minikinImageBytes = textByte; /*File.ReadAllBytes(path);*/
                }
            }, "Pick your Minikin selfie!");

            yield break;
        }
        else
        {
            yield break;
        }
    }```
#

NativeGallery.LoadImageAtPath loads an image from the gallery path and turns it into a texture2D.

#

I have also tried using ReadAllBytes(path) to pass the bytes to a new texture 2d and then encoding, but that does not work wither.

rigid island
lean sail
#

🤔 why is this a coroutine also, am i missing something it looks like its just executing fully then breaking instead of just exiting a method

rigid island
#

gonna look at NativeGallery cause i haven't used it before

vast wyvern
rigid island
#

is there a reason they are saved as HEIC btw

#

is like a raw photo?

vast wyvern
#

iPhone default photo format is HEIC.

rigid island
#

but where are you writing this byte data?

#

i don't see it

vast wyvern
#

There IS an iphone setting to not use HEIC but for user accessability, we cant rely on users using that.

rigid island
#

understood

#

but I don't see you write that byte data into a file

vast wyvern
#

the API function passes byte[]

#

I have tested png and jpg/jpeg and that all works well

rigid island
#

maybe you do need conversion method

#

oh thats what NativeGallery should do yes, convert it ?

vast wyvern
#

Native Gallery returns a path. I THINk it converts in the LoadImageAtPath function but it is returning an error. Reached out to dev in their discord.

#

I am trying this right now:

    {
        if (checkAndObtainGalleryPermissions() == true)
        {
            minikinImageBytes = null;

            NativeGallery.GetImageFromGallery((path) =>
            {
                if (path != null)
                {
                    var tex = NativeGallery.LoadImageAtPath(path, -1, false);

                    var tempTex = new Texture2D(2, 2);

                    var tempBytes = File.ReadAllBytes(path);

                    if (tempTex.LoadImage(tempBytes, false))
                    {
                        var textByte = tex.EncodeToJPG();

                        minikinImageBytes = textByte; /*File.ReadAllBytes(path);*/

                    }

                    Destroy(tempTex);
                }
            }, "Pick your Minikin selfie!");

            yield break;
        }
        else
        {
            yield break;
        }
    }```
#

works with proper png and jpg images, now HEIC is left

rigid island
vast wyvern
#

yes

#

fixing some logic errors on the above lol

#
    {
        if (checkAndObtainGalleryPermissions() == true)
        {
            minikinImageBytes = null;

            NativeGallery.GetImageFromGallery((path) =>
            {
                if (path != null)
                {
                    //var tex = NativeGallery.LoadImageAtPath(path, -1, false);

                    var tempTex = new Texture2D(2, 2);

                    var tempBytes = File.ReadAllBytes(path);

                    if (tempTex.LoadImage(tempBytes, false))
                    {
                        var finalByte = tempTex.EncodeToJPG();

                        minikinImageBytes = finalByte; /*File.ReadAllBytes(path);*/

                    }
                    else
                    {
                        Debug.Log("Error");
                    }

                    Destroy(tempTex);
                }
            }, "Pick your Minikin selfie!");

            yield break;
        }
        else
        {
            yield break;
        }
    }```
#

This does not work either - BUT

I heard back from the dev of NativeGallery and he explained that NativeGallery.LoadImageAtPath, a function that converts the chosen image into a texture2D, only works on iOS and Android, not in edtior. Will report back on that if anyone else runs into a similar issue.

#

Thank you for the help everyone ❤️

vast wyvern
#

Also, my dumb*ss was saying heic when I meant heif

hollow hound
#

Why child colliders dont trigger onTrigger events in parent if the parent doesn't have rigidbody?

#

The other object has rigidbidy.
I getting results like this:

  1. Collider in child, parent has rigidbody. - parent triggers OnTriggerEnter.
  2. Collider in child, parent doesn't have rigidbody. - parent doesn't trigger OnTriggerEnter.
  3. Collider in parent, parent doesn't have rigidbody. - parent triggers OnTriggerEnter.
    Looks like very strange behaviour. Why is it working that way?
#

And is it possible to check for triggers/collisions in parent with collider in child without rigidbody (other object has rigidbody)?

wintry crescent
#

Hi, I think my unity is haunted
I'm on 2021.3.20
When I open a prefab, and move a random object, OnValidate on a completely different object, on a random script, on a completely different prefab, that exists in no scene, gets called.
what is going on

quartz folio
wintry crescent
hollow hound
#

If I move collider to parent or add rigidbody to parent, collision occurs.

wintry crescent
#

I did nothing else

#

the scene that I was on before I opened this prefab has no references to any of those prefabs

#

this is called on multiple scripts

#

this is ridiculous

#

wasn't OnValidate only meant to be called on a component when you change that particular component?

quartz folio
vast wyvern
#

this only works on mobile and not in editor though!

wintry crescent
green oyster
#

called when you change variables in that script

#

through the inspector or stuff

wintry crescent
#

have you seen the screenshots?

quartz folio
#

OnValidate is called at various stages during the Editor's normal operation, such as loading scenes and entering Play Mode.

#

Some notes I have made on this page

humble thicket
#

hey I got a system where I do my own raycasts to detect where the player is looking at on a canvas but im having trouble finding a way to link it up into the UI interaction system that unity has, i have the canvas position of where the player is looking and I just want to be able to interact with buttons e.g how can i do this

wintry crescent
terse garnet
#

guys, I'm trying to use the mouse to click and get the position of the world to set a destination for my player to walk, basically a click to walk, anyway, I'm using ScreenToWorldPoint and it even worked, but when I use the mouse to use the user interface it also takes that position, is there a way for the click to only identify when clicking on the environment?

quartz folio
#

I hate and do not use OnValidate because it's imo awful 😛

pure cliff
wintry crescent
quartz folio
terse garnet
#

humm nice

#

i will trie guys, thanks

quartz folio
hidden flicker
#

Hi I am losing my fucking mind over this problem. I am trying to instantiate the baked mesh of a gameobject. I try to access its Skinned Mesh Renderer through GetComponent. "limbMesh.GetComponent<SkinnedMeshRenderer>().BakeMesh(ex, true);"
And then I instantiate it. "Instantiate(ex);" However, I keep getting a Null Reference Exception error. Help because I want to remove my eyes with pliers at the moment ❤️

#

It should be the simplest thing in the fucking world why isn't it working why isn't it working why isn't it working why isn't it working

quartz folio
#

What are you passing in as ex?

hidden flicker
#

It's properly referenced, too. In the inspector, the ex variable is public and IS SET TO THE SKINNED MESH RENDERER BUT IT SAYS IT'S MISSING

wintry crescent
hidden flicker
quartz folio
#

No, it gets populated by it

high knot
#

does anyone if all the code is stored in the Scripts folder?

quartz folio
#

it cannot assign anything, it's not passed by ref

hidden flicker
#

How do I fix it

#

Thank you for the help by the way

quartz folio
#

Make a new mesh and pass it in

hidden flicker
#

I already declared it at the top of the script as a Mesh

quartz folio
#

But did you assign it a value?

hidden flicker
#

There are no code errors

hidden flicker
quartz folio
#

If not, it is null

#

Again, it cannot assign anything, it's not passed by ref

#

it populates what you pass in

grizzled needle
#

Would Vector3.Angle() return the angle between two directions even if they aren't normalized? or would that skew the angle?

#

I'm reading the documentation right now, and I'm not seeing anything about that

hidden flicker
rain minnow
quartz folio
hidden flicker
#

I'm not passing in a mesh, I'm passing in a skinned mesh renderer

#

And expecting a mesh out

quartz folio
#

No you're not, you're calling the function on a SMR, and passing in a Mesh variable which is assigned as null

hidden flicker
#

"new Mesh ex = limbMesh.GetComponent<SkinnedMeshRenderer>().BakeMesh(ex, true);" like this??

quartz folio
#

you need to pass in a Mesh variable that is actually assigned to a new Mesh

hidden flicker
#

That gives me an error

quartz folio
#
ex = new Mesh();
#

Then use it

hidden flicker
#

Thank you

topaz ocean
#

how do I handle events triggered in a parent object inside of a child object script?

river sentinel
#

This is less of a code issue but still confusing: My controller works with the New Input System with one project. But there's another project where it just doesn't. I can bind inputs using the controller but once I get in game it's completely ignored. What is happening here?

#

Both projects are using the same Unity version: 2022.1.23f1