#archived-code-general
1 messages · Page 166 of 1
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
I'm not using monobehavior so idk if that is an issue but the inputaction works without enabling the script
wdym by returns false? do you mean the first condition is always false?
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?
EventSystem.current.IsPointerOverGameObject(0) returns false even when I would expect it to return true
how are you using StartCoroutine if you aren't using a monobehaviour?
sorry I am, I am lying I am using a namespace that uses monobehaviour
For RotateAround(), how do you control how far away from the center/point the rotating transforms are? Like in terms of radius
do you perhaps mean you are inheriting from a class that inherits from monobehaviour? namespaces are irrelevant here
okay then yes, new to this
is the object you are expecting it to detect a UI object or a world space object?
It is, it's the selected object here:
It is enabled by scripts when I run the game btw
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
How do look at what it is detecting?
should be in the preview window at the bottom of the inspector window
look at it during play mode
is this what you are talking about?
yes
huh, theres nothing there
do your buttons work
Yes
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
oh, when I click something it goes into selected. I'm just dumb lol
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?
Yo, I just had this question a couple weeks ago, and it was driving me crazy.
I eventually decided to ignore it, because I was seeing these spikes even in a totally blank scene profiled in a build on Windows. So I think it's unavoidable?
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
Try to get the hierarchy tab displayed for your profiler. I really forgot where the button is to display it, but it will tell you if its in the editor or player loop.
After that, if its in the editor loop then swap your profiler to edit mode and you can see in more detail
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?
@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
thank you very much everyone! i'll try everything right now
this?
yes
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
ohh that
it's playerloop
oh.. so it's my code then..
or this
whatever it is
full expansion
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
doesn't this produce a 6fps frame?
it shows a ~160ms clip
oh i didn't see it was that big. yeah, you want to dig into the hierarchy tab and see if any insight
this one produced about 70% if i remmeber correctly
If it's just Other and you cant find any clues, then it might be something in your code
remember*
screenshot the full profiler, hard to judge performance otherwise
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
you'll need to expand the top ones
it kind of stops there
not sure
maybe it has some hidden elements i need to toggle on?
You can click "Deep Profile" at the top, it adds stuff. Might not help, but worth a shot
ohh okay
just be careful, can eat your RAM up and crash Unity if you have a large project
502b is a lot of alloc
502 bytes, how do i know what code allocates memory?
Can you show more of what's under behaviourupdate
Well something is clearly going on involving Sprites
Some update loop is doing a lot of alloc
this is all i could fit
are you instantiating or destroying Sprites?
"Sprite" is just another term i use for "Object"
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?
it's a special gameobject that uses an abstract class Sprite that uses MonoBehaviour
oh, you have made a monobehaviour called sprite?
show the Update code
there seems to be something in your code where all those objects are doing a bunch of work on the same frame.
Is that 348B alloc on sprite as well, I'm on mobile cant really see if that one lines up
my Update is actually a virtual function, so a lot of functions use it
i think it's the Player function though
It has to be on a gameobject
yeah, i think it has to do with text?
might be my monitors
i'll try disabling them
my monitors keep track of some variables and print them
you can use a profile marker https://docs.unity3d.com/ScriptReference/Unity.Profiling.ProfilerMarker.html
With the gameobject name to see which Sprite is having the issue
Ye but I don't wanna have an empty prefab with the script attached for no reason other than to be on the list
Is there no other way
Well I believe you have to... if you're worried about performance, it's not an issue
Your naming might need some work as well 😅, sprite and monitors is very confusing to read and think that this is code
I'm worried about cluttering. It just seems like having twice as many files is pointless
twice as many BaseUpgrades
by files do you mean your hierarchy is cluttered when in play mode? If so, you can work around that
oh, monitor's just this guy on the side of the screen
so much potential, pretty worth it
it doesn't use a class, so it won't show in profiler
Sorry no. What i mean is that for every BaseUpgrade script, I would have to have an empty prefab in the assets folder with that script attached, while basically doubles the amount of prefabs. It just seems very inefficient
wait, it does actually
That's not how you'd approach it
does Debug.DrawRay (for raycasts) cause lag?
it was in my code
probably was being called over 10 times
Use Dependency Injection
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"
You'd serialize the BaseUpgrade script, then when you run your game, you de-serialize it into a new BaseUpgrade you instantiated.. you then attach that to an instantiated gameObject
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
you could use colliders?
But I don't want to add the items to/create the list on run-time. The BaseUpgrade is an abstract class that i use to generalise in the list. I have multiple different children of this class and I just want to put those children scripts into the availableUpgrades List in the inspector which would require prefabs
Why do you need it in the inspector
so like, how to calculate if a position is in a certain range of something else?
Yea I tried but isn’t it weird to collide with something and it happens?
With a physics overlap I think
I’m not too sure
for OnCollisionEnter, set a boolean to true. then in update, put (if bool == true && user presses e) {Do something()}
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
I know nothing about physics but if you just wanna calculate raw distance between two things you can go for https://docs.unity3d.com/ScriptReference/Vector3.Distance.html
I should do it a trigger but thanks for the idea appreciate it
Sounds like a potential case for ScriptableObjects, but it's kinda hard to follow at this point
aight, thats fine. I would use Dependency Injection + Strategy Pattern
Using an Enum as your identifier to select your applicable upgrade object
man you really like that strategy pattern, huh?
They wont work because the upgrades need functions themselves
yeah its extremely applicable to video games
which scriptable objects cant have from my knowledge
You can call functions from a different class, and have them pull in data from the scriptable objects
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
yes but each function is different, and the functions are not used until the player gets the upgrade. Then i would do a for() loop in a currentUpgrades list and call the function generally: currentUpgrades[x].DoUpgrade
then can have functions, it's just that you'll be making a new Scriptable Object script for each one
The DoUpgrade function is overriden in each child of BaseUpgrade and so do different things
Let me know if you need further info for my answer I gave, its very likely what you want
I'll have a look into it
base classes and interfaces still exist for Scriptable Objects
SOs are the way to go. I don't know who told you they can't have methods, but they can. If you let them have state it gets trickier, but if they're stateless and just do something to the caller it'll work well
SO still doesnt make sense, there's no reason for your "ability upgrade" conceptual thing to have a transform
just use a POCO
? SO do not have transforms, they're not components
arent they still mono behaviors?
no
what is a POCO
no
all that stuff also isnt needed
not Update
Plain Ole C Object, a vanilla class
so whats the difference between an SO and a static class?
it just lets you add it in the inspector?
From what I know, SO only exist to contain variables and data, not functions
my main gripe is SOs also wont be abstractable, you cant interface em and ref the interface instead for your referencing game object
SO's are for storing immutable data, easily changed using the inspector; they can have functions like any other class
i hope by "static class" you just mean "regular non-UnityEngine.Object class"
but you can create instances of SOs that are assets in your project. they also have a few messages they receive similarly to MBs like Awake and OnDestroy
which means you tightly couple your logic to the concrete class, which makes it way harder to do mocking and whatnot for testability
No I meant static class
why would you compare something that requires instances to a static class?
Isnt it literally a static method you use to get the SO "instance" anyways
its like a weirdly obfuscated pseudo static (but not) class
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
it just seems to weirdly "Im gonna do 8 steps to re-invent the POCO"
Because the DoUpgrade() is different in each child class
which wouldn't happen with SO
I think maybe you should read up on SOs
yes you can
from what I have seen... SOs seem like a lot of extra steps when you can just use a POCO and DI
you'd be terribly mistaken
ah yes, a static method that creates a single instance is definitely the same as a static class. that's why all of your components are static classes because you use Instantiate to create instances of the objects in the scene
you can override methods in SOs?
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
you can have an instance of a scriptable object as an asset in the project. you cannot do the same with a poco
yes, just like any other virtual function if you inherit from it's class
My understanding was that SOs were just convenient containers for data storage
same
SOs are instances, independent of objects. Static members, fields and types are defined as part of something.
pretty much, except "convenient" just means to me "refusing to use a POCO that already does that"
in terms of actual implementation, like your end result
POCO?
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
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
How would I do this though. What class would I be inheriting from
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.
with SO's you can change values during playmode and have it effect immediately without a stop and code compile, great for testing
you can have more than one instance of a scriptable object. a static class doesn't even have instances
oh, Plain Old Container Objects?
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
there are beginner courses pinned in #💻┃code-beginner
Plain Ole C Object, or Plain Ole Class, etc etc. Vanilla classes
I would think of SO as more like a regular class or struct that's accessible from the inspector (a field)
yeah thats what I have been saying, you go through all these hoops so you can drag and drop it onto a field in the inspector
How's this relate to static though?
because the end result is you cant Mock it
its a tightly coupled static relationship
What? Immutable?
Sure its technically an instance, but the point is you are 1:1 tightly coupled to the concrete now
they allow for easy switching. In a gun script, you'd only have to change the currentGun scriptableobject value to change every stat. Without them, you'd have to go access the script and change each value with a method.
Thats what strategy pattern is for
dont those only apply to unity 2019 and not unity 2022
the api has not changed that much
It's just data placed elsewhere.. A want-to-be globally defined data.
Hopefully no one associates static with global.
the issue is the tightly coupled 1:1 problem
Like you cant (easily without doing wild stuff with reflection) mock it
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
are you doing game dev, Enterprise Edition™? My experience is this is almost never worthwhile, certainly not for volatile game logic
Strategy pattern is effectively:
- 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
- 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)
- Your prefabs just have a serialized field for the Enum, which is a dropdown, to pick what strategy(ies) they have
- 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)
I feel like
You’re unintentionally overcomplicating your system
so BaseUpgrade would be public class BaseUpgrade : ScriptableObject with the virtual functions
but I still can't assign it in the inspector
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
Why not have each class store that logic itself and have it called through like, Inheritance?
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.
Why do you say so
I guess its just two ways of doing the same thing, but more decoupled from a central manager class?
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
testability and mockability, makes it a whole lot easier to keep track of your stack trace
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
Inheritance can seriously muck up your order of "wait where did this happen"
Hmm fair enough
what do you mean?
ngl never seen StrategyManagers before
Thats an arbitrary name I made up there, that thing just has to hold the list of all your strategies and map em to the enum
I can see the benefits of both ways, but if you 100% want editor inspector functionality then Scriptable Objects would be easier imo
I get what you mean but it still feels inefficient to use scriptableobjects
God organizing Unity code is hard, I've been mulling over how to do something for like an hour rofl
I would only create 1 for the type of upgrade and then move on to the next upgrade
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];
}
upgrade a would only have 1 SO a, upgrade b only 1 SO b, etc etc
it should be typically quite simple and is, for all intents and purposes, usually just some variation of a readonly dictionary
is Strategies a real thing or just a variable name
Learn dictionaries asap PQ, they're super nice
In fact usually I make it literally just a ReadonlyDictionary<TheEnum, TheInterface>
ye I saw something saying to use them but they seemed arbitrary
a class + interface you would make, those hold the unique implementations of your logic these things can do
well if you can make the SO's more generic, e.g Melee instead of Chainsaw. Then create lots of SO's using that one script and then you can have a Chainsaw asset with the custom values of the Melee SO.
Dictionaries are incredible
except each upgrade varies vastly from the last, or not at all. That's what put me off of SO
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)
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
They are a mapping of a Hashset Binary Search tree to a value
just read some tutorials about it
and then that item has its own things and variables
on it
@indigo arrow does everything I wrote make sense or you got any questions?
What differentiates abstract classes and interfaces
You can only have 1 parent (inheritance) in C#.
You can implement as many interfaces as you want.
Interfaces are like a "job" your class says it has, and with that comes a contractual obligation to implement the stuff the interface says you have to have
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
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
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
henceforth I should use abstract classes and not interfaces no?
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
ye no worries
in that aspect you can do the exact same thing with interfaces
it was more of a general question
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
True, but abstract classes communicate better what this object "is" in the grand scheme of things
I understand how dictionaries work now, but how do they solve my "Add upgrade scripts to a list in the inspector"
1 major thing is you cant inherit multiple classes, but can multiple interfaces
Admittedly I rarely use interfaces tbh
i dunno, but i bet you will find some use for them
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
I only use abstract classes in 2 cases:
- I am forced to because I am already using inheritance to get functionality
- The thing is serializable
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
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?
I am basically trying to create the item system EnterTheGungeon has
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
where the pickups grant you some sort of stat boost or ability
Thats actually a good rule, I'm going to keep this in mind myself
I see the logic there
Do you have any further info you need with respect to my solution? It should be solid and exactly what you are asking for
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
I have my services as the owners of the GameObjects.
So my pattern I follow is my MonoBehaviors only really have the following:
- "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)
- 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.
Youd have an Enum dropdown on your MonoBehavior of all your strategies. You pick the ones applicable and done
Its not a bad idea, and delegating all responsibility to the manager was something I considered. But I'm experimenting with delegating a little more responsibility to GameObjects
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
I still dont understand what you mean by stratergy
as in like, rendering the visuals for what the command "looks like" in the UI (drawn arrows or drawn lines or highlighted areas and stuff)?
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!
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
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
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?
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?
classes are not objects. Classes are blueprints of objects
kind of like a class prototype in JS
not really sure the terminology because i hate JS
prototypes are objects in js unfortunately!
you have to make an instance of the class to actually have an object in C#
i'm well aware
i'm asking how to solve this design problem within that framework
since i can't apply my usual methods
I don't understand your usual methods
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
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
You can do exactly that in C#
i can't instantiate them first because they're monobehaviours
That's your problem
which means they need an object to attach to
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
yeah i mentioned that possibility but i really don't like it because it feels completely redundant
Then just go with the first way
That would be most Unityish way though
A list of prefabs or ScriptableObjects
a list of scriptableobjects doesn't help me get monobehaviours into the scene, but i guess you're saying not to do that anyway
If you want Monobehaviours in the scene you'll be Instantiating prefabs most likely anyway
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
oh sick, i'll look into that as well then
and try it without monobehaviours i suppose
thanks for your help
Do you have specific parts of my stuff I outlined you have questions about? I feel like I went pretty deep into detail
Strategy just means the like, chunks of unique logic
when i want something to happen, or what i want to happen
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
ah alright
i understand now
and i'd group them using a list or a dictionary or what
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?
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
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;
}```
either you're removing relevant lines of code or some component on CurrentWeapon has an OnDisable method changing the value
{
_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?
what does swapWeapon point to? because if it points to CurrentWeapon's component then of course that OnDisable is the issue
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
is it better to use a switch statement for this or should i let this code be?
https://hatebin.com/bqtezhoovq
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
This is an indication that you might want to conceptualize those element:
Strategy pattern could be use here. However, I'm sure you going to have more and more rules that are being added overtime and you should start to pivot towards a state machine.
https://en.wikipedia.org/wiki/State_pattern
https://en.wikipedia.org/wiki/Strategy_pattern
SlidingState
AirState
GroundedState
I don't see the "save scenes" as a selection
I was watching a video and they had "save scenes"
this is a code channel
its not save scene anymore
it's just Save
you see they have the same shortcut right and the editors versions are wildly different?
oh sorry
Does that mean you can't create scene anymore or something?
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)
doesn't mean that at all.. They just renamed the menu.
you're still working within a scene
I'm doing this in code in runtime btw... Just wondering if I should do it via the Mesh class or other method
No?
It means just click save
ok
Is there any way to make it so that an input field does not lose focus when clicking out of it
uhh maybe forcing the element to focused on via script when clicking around or w/e condition
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
why old?
The way I have this set up works perfectly and I don't want to re code it, I know its lazy
the text quality esp on the old Inputs fields is garbage lol
tmp is the way 👍
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)
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?
Oh sweet!
Best way would be to parse it once as well then store it all in memory. If its gonna happen often, opening a file is really slow
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
you could
a scriptable object could probably work too
you probably wouldnt want a bunch of text files all storing a few lines tbh, randomly choosing a file can be somewhat weird
you could make it a text asset and put that inside an array
pick random index from array
parse the textasset
Depending on datasize you may want to consider a small database instead, if you want to reduce memory while still having decent read speeds
in my "game" i read in and parse files with hundreds of lines each time a round is started and you don't even notice any performance issues, as long as you don't need tens of thousands of strings, really any approach is probably fine and not worth overthinking 🤷♂️
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
Maybe the string is empty
Log it's value before use (before the very line)
I can confirm that it’s not empty
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?
The value I expected? Not sure why that’s relevant
It resolved two concerns.
One, if the line is being read.
Two, if the string is correct and not assumed to be correct.
are you looking in the scene view or game view?
I believe that one might only be scene view
Scene view, all gizmos enabled
can you try it with OnDrawGizmos
I don’t think so, as Handles.Lables can only be ran inside OnGUI?
Could be misunderstanding
ah maybe im thinking of the wrong thing, ill test something quick
I've only ever used it in OnSceneGUI
from the docs and other examples online, seems like everyone this as an editor script and OnSceneGUI
That’s why I was curious if it was exclusive to editor scripts or not
why dont the colour in the inspector and the actual colour match
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;
what's the default color of the texture
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
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)
You shouldn't be using the extensions
!vscode
Nevermind, the tutorial suggests an extension (which Ive never used and it worked fine)
Anyway, follow that
Is the 'Go to type definition' appearing for you when you right click a method call?
Check your C# and C# Dev Kit extensions are upgraded to the latest versions.
Yeah, it works fine with me and sends me to the c++ or where I define the method
@quartz folio @hidden parrot not sure whats going on, but the color codes are suddenly different
and I didnt do anything different
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?
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 😛
what do you suggest?
visual studio/rider are the 2 real options
if you have access to JetBrains Rider (students can get it via the github student program) then I highly recommend it
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
well the real issue is that you're using vscode, and the extension is still a preview
visual studio is a thing
Try the VS ide (non code)
ooh
The debugger is built-in to the new extension afaik
you shouldn't have the old one installed
Alright, I'm downloading vs ide now, let you guys know how it goes, appreciate the help
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
What are you using OnValidate for that requires a build?
onvalidate from what i know is just when your cursor is over the unity element
but yeah it does not work in build
Nah, OnValidate is when an inspector value is changed + another call I don't remember
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
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
The 'Go to type definition' option is also missing in the vs ide 🤔
Does it happen only when you spawn that object from something that is marked DontDestroyOnLoad?
Or does it happen always when spawning that object
how to untag object from script?
It seems to be happening only in this specific situation, I've spawned other objects without trouble in other circumstances
Most likely tag = null; or tag = "";. I'd try the first one and see if it works
ok
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
Have you tested spawning this particular object from a non-DonDestroyOnLoad object? Or spawning something else from within that same script?
I will try to do so, will let you know, thank you
It would appear as though what's causing the issue is spawning it "from" an object in DontDestroyOnLoad.
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....
Setting it to null seems to trigger a Unity warning. Maybe setting it to "Untagged" would work
hello .... I added a button and it just simply doesnt work... idk why , didnt even added a script
I mean its not fading in
I feel like that's way too vague for anyone to try and help you. You should add more context
can I send vid recored from phone ?
wait i will re rec it
It would be more useful to describe what you're trying to achieve (with words, no technicallity, just the "idea").
Then explain how you did it, and what the current result is
I think I know what could be the issue. Try either:
- spawning it, and at the same time attaching it to a parent that's not marked DontDestroyOnLoad (in the same frame)
- spawning it, and marking it DontDestroyOnLoad
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
its in a canvas which have to pop up before the match starts... now in that canvas I added a button with character sprite and tested in yesterday it was fine, I didnt changed anything and closed the project and slept... now when I open the unity (restarted 10 times) it doesnt work for no reason
The reason for that, is that an object must be assigned to a scene, always - because you can technically load or unload multiple scenes at a time. And if you spawn an object from DontDestroyOnLoad that isn't marked DontDestroyOnLoad, it might not know where to spawn it - which means it's a sceneless object, which might mean unity must get rid of it
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)
I'm pretty sure you cannot have a child gameobject of a non-DontDestroyOnLoad object, that is DontDestroyOnLoad
Just attaching it to the Bone in question is also causing it to get destroyed.
Oh, so you would spawn it with the Bone in the Instantiate function, not attach it afterwards
Hm. What if you mark it as DontDestroyOnLoad while spawning it as child of the gameobject that is doing the spawning?
you can try that yea
Problem is, it absolutely needs to be child of another gameobject because it's basically me trying to attach an object to my character's Hand
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?
And my character is in DontDestroyOnLoad
a workaround could be, that you attach a script to your character's head (maybe a singleton) in which you spawn it, and then call that from the DontDestroyOnLoad object
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
Not sure I understand your first sentence
My script is already essentially attached to my character (which is inside DontDestroyOnLoad)
Does your character have to be DDOL in the first place?
the character is in DontDestroyOnLoad?
were you marking the new object as DontDestroyOnLoad when you were spawning it?
Yes, it's an episode based game, where we keep the player spawned for valid reasons and move it between "places"
It work only tag="untaggeg"
I've tried both, marking it and not marking it. Both lead to its destruction
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 👍
try spawning it with
_heldItem = Instantiate(i.Prefab);
DontDestroyOnLoad(_heldItem);
_heldItem.transform.parent = parent;
that is such a weird issue though
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
I assumed parent is whatever you want the parent of that object to be
I don't know if you want the spawned object to be the child of the object that's doing the spawning, or something else
which unity version are you using? I made a test script, and everything seems to work properly on 2021.3.20
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
and the result
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
Character is doing the spawning. I want it attached to a child GameObject within the Rig. A bone if you will
2022.3.2f1
I see, maybe there's a bug?
can you attatch my code I sent above to any new gameobject in your scene?
Interesting that your code uses the Start function but changes the return type. Unity calls those function by string? That's wild
Start can be a coroutine, but nothing else
Oh i see, thanks
Your script works fine.
I've attached it to a random gameobject in my scene, it got moved to DDoL and instantiated everything. All 3 are present
that's even more weird... there's something wrong with your objects maybe? I really have no clue
try removing things gradually, to see when it breaks
just make backup copies before you do so :P
Yes, I'll keep digging, but it is indeed pretty weird
so you don't have to recreate the objects later
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
!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.
I programmed a code that should open door in 2 directions according to the player facing but the door is just opening and closing in one direction, here are the scripts: https://gdl.space/ulelutaquw.cs || https://gdl.space/xupuvemihe.cs ** https://gdl.space/ivogivezac.cs
This is my animator in the screenshot
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?
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.
And the other one too please
what arrow?
Seems good to me
So debug.log the dot product.
okay
I dont think I debug.logged it correctly
what line do I need to add
I just added Debug.Log("dot")
remove the quotes
And then open it straight in front of the door, and then straight back of the door.
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);
nope still opens the same way
Still the same debugs too?
no there are other debugs tho
let me screenshot them
its gonna be some really obvious mistake
FirstPersonController.instance.transform.position probably this then
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
Can you debug.log FirstPersonController.instance.transform.position too on all 3 dot debugs?
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.
We will see 🙂
Blue arrow is forwards btw
So your blue arrow points upwards
And you are always on the floor
what does that exactly mean?
So you are always at the back of the door
oh
what did I do wrong
I downloaded blender 1st time in my life today
maybe thats why
You can probably instead of Vector3 doorTransformDirection = transform.forward; do Vector3 doorTransformDirection = transform.up;
As a temp fix
yea kinda works but in the other direction
so basically Im facing north and the door opens south
and the other way around
how do I fix it?
In Unity 3D, the blue arrow is always the forward of an object
Not a problem, now you know 🙂
do you have an idea of how to fix it?
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
yea I always get it mixed up
let me try
does anybody know how to apply rotation and scale in blender?
ty
Hey, I can't see Dynamic Parameters on the inspector for UnityEvents
like what?
did you create a method with compatible param
what ?
I fixed it I just set dot = -dot
why not fix the forward lol
` 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.
i mean u could just create the empty gameobject and fix it that way
you cant use enum as dynamic param
ig, either way it works
btw ty to everyone whos been helping me
did I use?
what is CarPartCategoryUi?
public class CarPartCategoryUi : CityComponent { public Toggle toggle; public CameraController selectionCamera; public CameraController freeCamera; }
yeah this is 100% not going to show int he inspector
oh its a custom class
UnityEvent only supports simple parameters
And CityComponent is a Monobehaviour
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
I kinda remember that I was able to pass parameters from the inspector
Yes, only simple ones
Either primitives like numbers, bools, strings or UnityEngine.Object
use delegate or Action and do it via code to pass objects @jade kindle
No, I could pass CarPartCategoryUi. But now It doesn't show up under Dynamic Parameters
cause a class is not a dynamic parameter
In the code you can do anything you want. In the inspector only simply types will be supported
Thank you
So the inspector is mostly useless
like unity itself
being inspector bound is limiting and also very confusing to find things
yes, but if I would develop a game engine I would not limit the passable parameters with some hardcoded types like string, int, etc.
Go ahead and make that engine then!
they probably limited it to simple value types for a reason xD
you should not be using inspector anyway if you want complexities
id love to see what u come up with instead lol
yes I should not, but i think I should be able to
What are some good challenges for intermediates?
what's a google challenge?
*good
I just got a pixel and they are already brainwashing me
Try to make a simple board game like chess or checkers
Alright, thanks guys
the first question can be modified as: return the sum of two number...without using any arithmetic operator....
huh
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);
Probably a #🌐┃web question
Should I learn c# before learning unoty
You can't load a file using a HTTP path - you'll need the location of the file relative to the binary
It's hard to program unity games without knowing c#, imho, so yes
K
Should I watch the 9h video for caharp
🤷♂️
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#"
Ah ok. So, download it first then read it.
Everyone learns in their own way. Some read books, other watch videos and some read straight from the documentation
But yeah, a 9h video isn't that long and should keep you interested, so it's a better start than none
Yeah I don't know the exact way to do that off the top of my head, but you're doing the equivalent of trying to open a file on your game server's hard drive using a URL
There's no built in functionality in Texture2d.LoadImage to do that
I'm going to see if something like this works: ```
WebClient client = new WebClient();
byte[] fileData = client.DownloadData("https://example.com/file.txt");
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
This might work but also might not since there's restrictions in webgl for this - cross domain exploit reasons
Pass them as parameters?
Right now the class in question is static
That's fine..?
Can you inject stuff into static classes?
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 */ }
}
Oh no not like that, I mean the static class "dispenses" the prefabs
You can probably load the prefabs into the library with Resources.Load and then use your static method to access the loaded prefabs
public static class AdjacencyHelper {
public static GameObject getConnection(Pair<int, int> source, Pair<int, int> dest) {
...
}
I'll look into this
tyty
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..?
Kinda, but these prefabs don't have any logic, they're just visual components that I'll create and destroy
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
each unit has a class that manages these arrows (arrows are the prefabs)
Right now I can make each of the managers have references to the Arrow Prefabs no problem, but it feels like overkill to pass that many references around since there will be a lot of these managers (one for each unit)
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.
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?
So my approach I have been using is as such:
-
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 -
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
-
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.
-
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
can anyone suggest a book for unity game development?
Unity changes pretty quickly from year to year, I don't think books are where the best information/learning exists (I could be wrong).
I am trying unity learn pathway to learn right now
any suggestions?
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?
I am learning through Unity Learn
What do you suggest?
Find() and all the others aren't threaded, so there's no need to "delay other functions" until they're completed. If it takes ten seconds to execute Find() then your game will hang for ten seconds (as expected). If you're running into performance issues, then address it later - don't worry about it now until you have your head around why it's slow, if it is slow.
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
ok thanks
(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.
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.
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
Pretty much where I was headed - I was just curious whether having Find-likes trigger an event upon completion was viable at all
you could do that, but that sounds incredibly messy
(like, pub/sub isn't really the best application for that pattern, imho)
Fair enough! So better to not use it then
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
Thank you @modern creek and @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
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
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?
You may need to explain that better. What are the expected results vs what are you getting?
The expected result is that the beat timer doesn't send a "next beat message" until after the specified period of time (0.5s in this case) has passed.
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.
What's the code you're currently using?
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?
Yes, exactly
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;
}
}
}
}
}
For our purposes, yes, in an Update method. (The reality is more nuanced, but it's definitely in that phase of the player loop.)
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?
What happens if you yield return null instead of yield _ticker.Tick() in your Test?
Then nothing is updated. This is expected, as _ticker.Tick updates my entity systems.
Are you sure that the issue is actually caused by the TimerSystem and not caused by your Test?
No. I'm still trying to diagnose this, and I could use some ideas.
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
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.)
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 🤣
How so?
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 ???
just add another material to the renderer
both will be used
thanks but would the alpha of the top material ( magic ) effect the alpha of the base material ( red ) ?
no
i don't understand that
obviously one of them will need to be transparent or cutout if that's what you're asking
ok well , you did answer the question , thanks a lot ❤️ ❤️
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 sameTime.deltaTimevalue.
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.
You can use multiple Materials for a Mesh, but afaik you can't use multiple Materials on the same part of geometry, so the answer to your question is probably "no".
To me, it sounds like you're in need of a Shader! (Or VFX)
i'm not sure if you are correct about that , the mesh renderer by default has a list of materials
clearly we can add on over the other
Adding multiple Materials in there won't do anything if your Mesh doesn't have multiple Materials assigned to it (from your 3D Modeling App) as well, if I'm not mistaken, and afaik a 3D Modeling App won't allow multiple Materials for the same part of geometry
even if one was transparent ?
[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
Unity cannot serialize dictionaries
Even if one was transparent, Material is Material, but pretty sure that a Shader could be helpful, or a VFX that's emitting from the Mesh Geometry
Damn.. I'm out of ideas, so sorry!
Dang. Well, thanks anyway.
I was hoping SerializedScriptableObject could do it, darn...
Is there an alternative where I can make this work? I am using Odin here
You could, as a dirty workaround, create your own Serializable class that's representing a Key/Value pair, and construct a Dictionary from it on runtime
[Serializable]
class KeyValuePair
{
SomeType _Key;
OtherType _Value;
}
public class SomeSO : ScriptableObject
{
KeyValuePair[] _PseudoDictionary;
Dictionary<X, Y> CreateDictionary()
{
return ...
}
}
it actually worked ,i have just tried it
i can see a mix between both colors controlled by alpha
but it also said this warrning
Interesting... Thank you!
Odin an serialize dictionaries. Or you can find a serializable dictionary, or you can just serialize this thing as a list of key/value pairs (custom struct or class)
that last one is best I think because relying on odin serializer isn't a great move
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
Yes I am not happy with that solution at all, but it is interesting to know this... Mmm...
Omg SerializedDictionary exists
AND IT WORKS
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!
yeah just FYI SerializedDictionary does exactly that under the hood
it just serializes as a list of key/value pairs
Is is possible (and if so, advisable) to change the game object icons in the hierarchy?
It’ll make working with prefabs more annoying. If you need a better hierarchy view use something like https://github.com/WooshiiDev/HierarchyDecorator
Thanks for the link. More annoying how?
You won’t see the icon anymore so can’t differentiate prefab from regular object
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
Is there any way to set an Animation Curve to a Preset in code?
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
So I have created one in the Editor. Was wondering if there was an easy way to pick that out.
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
That's what i figured. I suppose ill go that route than. Thank you
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
normalize the velocity and multiply that by your desired speed
var rb = hit.rigidbody;
rb.velocity = Vector3.ClampMagnitude(rb.velocity, 0.5f);```
ah ok ty
also if that hit is a RaycastHit or RaycastHit2D you don't need to getcomponent for the rigidbody, it has a rigidbody property
good point
yea the only reason I have that code is for when I spawn in a capsule on the object but I could be just confusing my self
it's also working with vr hands that I have
Thanks for your help though 😄
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
by "not working" do you mean it instantly appears at the mouse position instead of moving from the player to the mouse position?
yeah
that's because you are moving it 1000 units per second
also you should be moving it from its current position to the target position
Okay I just did that and it worked
why
player.transform.pos should be the same no?
since it got instantiated at that position
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
I don't see why the bullet cares about player position
That line is definitely wrong
is it because it starts at the player position EVERY frame update?
no you were just doing it wrong. look up Vector3.MoveTowards to see how it works
<@&502884371011731486> i need to tell you something
What?
chat gpt told me something i never know it about moderators
I'll stop you now and tell you if you shitpost, you will be muted. So decide how you want to proceed.
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
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?
please i am respectiful i am following the rules right
It should continue up to the next yield, and then stop
Ok, so it does stop itself then. Do all coroutines go until the next yield when you stop them?
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
The order of updates always gets me when I'm working on complicated stuff with coroutines lol
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?
If the receiving function doesn't need to be able to store a reference to it, then I would recommend using ReadOnlySpan<T>. An array will implicitly cast to it:
public static void ReceiveSpan(ReadOnlySpan<int> numbers) {}
...
int[] array = new [] { 1, 2, 3, 4 };
ReceiveSpan(array);
Otherwise, you will either have to make a copy or use a wrapper object like ReadOnlyCollection<T>.
If the array never needs to mutate at all you can even store it in a readonly span from the start, to reduce costs
It will need to change, but I just want to restrict the receiver from doing so.
Is there any way to do it from the senders side?
What do you mean?
...disregard, I misunderstood something.
yea, if you copy the array first then send the copy
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
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!!
Hello !
Checking to see if anyone has had experience in converting HEIC photo files to different formats?
where is the code question in this?
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
if it's just raw byte data it should afaik
can you show what you tried so far?
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.
what exactly is and what isn't happening ?
🤔 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
gonna look at NativeGallery cause i haven't used it before
It previously had some coroutine business happening there but I changed it recently, valid point
This function is made to pick a photo from your gallery and pass it to an API that processes said image. The images you are primarily picking are selfies from a gallery, mostly iphone users.
iPhone default photo format is HEIC.
There IS an iphone setting to not use HEIC but for user accessability, we cant rely on users using that.
it is written to public byte[] minikinImageBytes which is then read by another script and sent through via an API request.
the API function passes byte[]
I have tested png and jpg/jpeg and that all works well
maybe you do need conversion method
oh thats what NativeGallery should do yes, convert it ?
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
and those pngs and jpgs also come from the photo library on device?
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 ❤️
Also, my dumb*ss was saying heic when I meant heif
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:
- Collider in child, parent has rigidbody. - parent triggers OnTriggerEnter.
- Collider in child, parent doesn't have rigidbody. - parent doesn't trigger OnTriggerEnter.
- 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)?
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
Does the other collider involved in the collision have a rigidbody?
The other object has rigidbidy.
Ah, it does. Then it should work regardless of whether this one does. Though it depends if you're moving this object. All movement should be done via rigidbodies if you're interacting with physics.
it's many scripts. I think if I change 1 thing in a random prefab, all OnValidates in all prefabs are called. That'd explain some slowdowns I've been having. Help please though.
Collider in child, parent doesn't have rigidbody (and collider). Other collider (target) has rigidbody and moved with force applying to rigidbody. No collision/trigger occurs in my parent.
If I move collider to parent or add rigidbody to parent, collision occurs.
I beg for help. Those screenshots are before and after I moved this prefab by 0.1
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?
I mean, it makes sense to me. There's a concept called compound colliders, colliders under rigidbodies become compound.
If there is no rigidbody, it's not compound, and the message is only sent to the object with the collider that was hit. If there is a rigidbody then it's sent to that object.
Reporting back, using NativeGallery.LoadImageAtPath(path, -1, false); loads HEIF images on iOS and is able to convert them via .EncodeToJPG/PNG. Good solution for anyone who is having this issue.
this only works on mobile and not in editor though!
it's called even when I load those prefabs into a scene during playmode... I didn't even touch anything, except spawn them in a scene. Why is it called?
onvalidates
called when you change variables in that script
through the inspector or stuff
well clearly my installation of unity disagrees
have you seen the screenshots?
Because that's how it works
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
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
alright, that's fine - but you must agree that what I sent in the screenshots ISN'T intended
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?
You have autosave on, if that prefab is instanced as all the listed objects, then it seems expected
I hate and do not use OnValidate because it's imo awful 😛
my code
raycast + layers
no, those prefabs that have OnValidate called are just random prefabs I opened in the past
this prefab is just random
I would check EventSystem.IsPointerOverGameObject
So what's towuniv-3? It is not a towbar pivot at all? If not then I imagine it's not intended, but as I said, it's awful, so who knows!
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
What are you passing in as ex?
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
oh wait, I think I get it now - it's a childobject of towuniv, which also contains, as a separate child, the object that has OnValidate called
I didn't expect that
I'm not passing in ex, ex gets assigned its value by BakeMesh
No, it gets populated by it
does anyone if all the code is stored in the Scripts folder?
it cannot assign anything, it's not passed by ref
Make a new mesh and pass it in
I already declared it at the top of the script as a Mesh
But did you assign it a value?
There are no code errors
No, BakeMesh assigns the value, right?
If not, it is null
Again, it cannot assign anything, it's not passed by ref
it populates what you pass in
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
So how do I pass it in
No, it returns void; it uses the mesh you pass in as the argument . . .
Make a new mesh instead of passing in null.
I'm not passing in a mesh, I'm passing in a skinned mesh renderer
And expecting a mesh out
No you're not, you're calling the function on a SMR, and passing in a Mesh variable which is assigned as null
"new Mesh ex = limbMesh.GetComponent<SkinnedMeshRenderer>().BakeMesh(ex, true);" like this??
you need to pass in a Mesh variable that is actually assigned to a new Mesh
That gives me an error
Thank you
how do I handle events triggered in a parent object inside of a child object script?
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