#archived-code-general
1 messages · Page 384 of 1
it will change in every object with that SO
so you make SO instances
but if I understand you correctly what's wrong with simple POCO's consumed by your monobehaviours
so you dont want to share variables you want to share variable declarations
tbf i dont understand this
well you say you want to share variables but you don't want one class changing the values used by another so what do you mean by sharing variables
My problem is this:
How do I avoid duplicating variables without using inheritance
You can use an interface
You won't be able to see your properties in the Inspector if you do so, though, on a field of the interface type
Inheritance works best here, especially when you don't know which of the 3 types you'll be getting at runtime
variables like health on objects would be great combined with inheritence. When it comes to actually taking damage you'd use an interface though.
A mix of both is usually ideal.
I watched some tutorials to make my ragdoll character with inverse kinematic arms to grab objects. This is my code https://paste.ofcode.org/8LiM3cwQthT8X3GmiLXffD. I used trigger enter because using my hands as a collider broke some things.
I made debug.break(); when it enters trigger and checked the fixed joint I create with script and anchor looked normal.
So I cant understand why joints break.
There is always the possibility to use composition, but I do not think you should. It increases the complexity considerably.
interfaces dont solve the duplicate problem, and inheritance quickly becomes massive and hard to manage
Then your problem cannot be solved without duplicating code
What is the actual issue here?
You can also us helper function. By example, if the issue is duplicate code in the damage taking, you could create a DamageCalculator
Sounds like an XY problem
for example in the game i have a lot of abilities, each of them have their own variables but some of them are the same in other abilities and so
so its a complete mess of same variables between different abilities
or with the stats i have the same
Why are they share though ?
sounds like duplicating code makes sense here though. If the abilities are different, they should have different metadata no?
by share i mean for example fireball and spear both have "int range" variable
Yeah, and you should have 2 classes with both different value.
Fireball
- int range
Fire Spear
- int range
Then in the ability you could use a "projectile" component if it should spawn something projectile-like?
Can you have different abilities with the same underlying C# type? Like a HealthPotion and a HarmPotion both have an amount to add/subtract from the health. Which means both could be two instances of the same class (one with a negative value, one with a positive one)
Scriptable objects can do that
yeah but writting int range in both of them is not good
Just have a function:
- Set(string name, T value)
- Get(string name, T value)
duplication isn't inherently bad. In this case it hardly seems like duplication.
The variables could be kept private/serialized, and to apply the ability the player would be injected into that
class HealAbility : IAbility
{
[SerializeField] private float _healAmount;
// Interface forces implementation of this method
public void Apply(Player player) => player.Health += _healAmount;
}
if objects are going to share a lot of logic - then using inheritence makes sense. Depending on how much the fireball and spear are going to share it can make sense to create a "Projectile" class for them - using generalized terms like direction and speed.
If they are wildly different and only share one or two variables it might be easier to use interfaces.
And if you do not know whatever the player has a health:
class HealAbility : IAbility
{
[SerializeField] private float _healAmount;
// Interface forces implementation of this method
public void Apply(Player player) {
if(player.Has("health"))
player.Set("health", player.Get("health") + _healAmount);
}
}
yeah theere is the issue. All abilities might share a few variables between them, so is not a lot of data but there are so many abilities with so many of them sharing a few variables between them
that using inheritance is really complex
not really. Just sharing the variables wouldn't be very complex? Where does the complexity arise?
Inheritance would be used to decrease complexity.
sharing general ideas between projectiles would make it easier to create another projectile later on no?
having the fireball - for example - use an interface specifically for abilities could be good. Have a general callback from the ability back to the user with a separate class to add knockback or heal the player would make sense here too.
can someone take a look
What part of inheritence do you want to avoid exactly?
making a big tree just for 1 variable shared on each pair of classes
btw is the setter useful? Cause if i want to change a variable i dont see any difference between changing directly the variable or creating a setter
if it's one variable, I think you can safely ignore inheritance. If it's shared behaviour between this variable, then inheritance can be convenient.
Usually, in such case you want to use composition.
https://en.wikipedia.org/wiki/Composition_over_inheritance
Composition over inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should favor polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) over inheritance from a base or parent class. Ideally all reuse ca...
they're nice if you want to do additional checks or run some method when setting the value.
If you just want to change the value then you wouldn't really need it.
im doing it for the stats, but inside the stats i have the same problem cause there are variables
and btw composition gets me into a problem, i cant change the values of the variables inside without putting them into public
cause its not inheritance
use [SerializeReference]
It should not, give more context and example.
not working
looks like the box becomes a child to my eyes - but I could be wrong. If that is the case, keep in mind that children follow their parent rotation and position in addition to physics. This can lead to strange behaviour. This box should not become a child when picked up. If that isn't the case then I don't know what the issue might be. Maybe try #⚛️┃physics ?
you'd need public for this.
There is so many things that are wrong there.
Read on it before...
[SerializeReference] is for making something visible in the inspector.
all my teachers say variables should be never public
And they are right.
i thought thats what serializefield do
Its not.
I've used it wrong all along?
And neither is SerializeField
oh my bad.
then your teachers are idiots and you can quote me
I add a fixedjoint to a gameobject that is on my tip of each arms and then connect box to the joint. I also tried to do the parenting before but couldnt.
they are half right. They should be both public and private in certain circumstances
It is for serializing reference as the same points out. You can show variable same if they are not serialized.
In what situation it should be public ?
There is situation where it changes nothing, but none as far as I know that they should.
when you want to control a value from another script...?
Maybe except for structure handling
Us properties in those times.
when you want to serialize it in a POCO
not really the case. You can use a property, but if you just want to change the value it becomes boilerplate no?
You use [SerializeField]
You can use properties, but those properties would still be public right?
It does not, C# has a really concept of properties.
that is a Unity attribute, not used by 3rd party serializers
THey are not variable.
In those case, you are right.
That being said, most serializier has their own properties.
I know ideally you want to isolate variables and use private - but wouldn't making them public be virtually the same as creating a property for them?
for this use case at least. Not in general of course.
In software systems, encapsulation refers to the bundling of data with the mechanisms or methods that operate on the data. It may also refer to the limiting of direct access to some of that data, such as an object's components. Essentially, encapsulation prevents external code from being concerned with the internal workings of an object.
Encaps...
It is a conceptual thing more than a pratical thing.
why would I make something private? I can't think of any reason than not making inspector more crowded.
wdym? any example
it has to do with good practice. Generally you only want other scripts to be able to access only and only what they need.
making things public exposes them, sometimes without reason, which is a big no-no.
To be honest though... when you're making your own game you can hold that shit together using duct tape, as long as it works. So you don't really have to stress that kind of stuff until you run into situations where you realize the actual issues it creates.
I think what's happening is that @steady moat is technically correct with everything they're saying - but you don't need to hold yourself to this standard when making stuff for fun. When coding production code and more advanced stuff you should hold yourself to these standards.
public float Health {get;set}
instead of
public float Health
Whats the difference
It was in the context of professor saying that you should not use public variable.
and the difference is... none whatsoever except code bloat when you use properties
personally, the professor is wrong.
a property is a varaible
what?
only way right?
Yes and no. They are functionally the same, however it handles you to protect what is exposed and what is not more easily. It states your intent.
And if you ever need to do stuff when you get/set the value, you do it in one place (at the property), instead of at all the call sites
in this case, it's the fastest and easiest solution.
using properties would yield the same result in your case.
C# conventions recommend you use properties to expose fields, but Unity pretty much doesn't care about properties lol
First, using SerializeField and SerializeReference make no sense at all.
C# conventions were designed for app dev not for game dev
also, wouldn't this be different in Unity?
We can't serialize this property right?
You can use [field: SerializeField] or use a backing field manually.
Ok so in here, if i want to have the Add method inside Player instead of Stats, there is no way to change the values of my _stats in Player without declaring public every variable on Stats class?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Stats
{
[SerializeField] int _hp;
[SerializeField] int _physicalDamage;
[SerializeField] int _magicalDamage;
[SerializeField] float _movementSpeed;
[SerializeField] float _attackSpeed;
[SerializeField] int _physicalDefense;
[SerializeField] int _magicalDefense;
[SerializeField] float _cooldownReduction;
public int Hp => _hp;
public int PhysicalDamage => _physicalDamage;
public int MagicalDamage => _magicalDamage;
public float MovementSpeed => _movementSpeed;
public float AttackSpeed => _attackSpeed;
public int PhysicalDefense => _physicalDefense;
public int MagicalDefense => _magicalDefense;
public float CooldownReduction => _cooldownReduction;
//TODO [SerializeField] float _range;
public Stats(int hp, int physicalDamage, int magicalDamage, float movementSpeed, float attackSpeed, int physicalDefense, int magicalDefense, float cooldownReduction)
{
_hp = hp;
_physicalDamage = physicalDamage;
_magicalDamage = magicalDamage;
_movementSpeed = movementSpeed;
_attackSpeed = attackSpeed;
_physicalDefense = physicalDefense;
_magicalDefense = magicalDefense;
_cooldownReduction = cooldownReduction;
}
public void Add(Stats other)
{
_hp += other._hp;
_physicalDamage += other._physicalDamage;
_magicalDamage += other._magicalDamage;
_movementSpeed += other._movementSpeed;
_attackSpeed += other._attackSpeed;
_physicalDefense += other._physicalDefense;
_magicalDefense += other._magicalDefense;
_cooldownReduction += other._cooldownReduction;
}
}
They could have at least used the conventions in place. But I guess other languages being supported in the past (which don't have properties) make interop more difficult
thats true
bear in mind when Unity implemented C# they knew absolutely nothing about it
right, but the backing field in this case would be exactly the same as just exposing the variable as public in the beginning right?
You mean differently that using "Class.Attribute = 1"?
No. it would be private
is that why they had JavaScript and Boo?
yep, Unity is a MacOs app
What case ?
Sounds like the ones who designed the architecture of a database at work lol
tell me about it
the case we're discussing
having a public property and a private variable vs a public variable would yield the same results here right?
public class Stats
{
[SerializeField] private float _health;
public float Health { get => _health; set => _health = value; }
}
For example, tables that have a 1 to 1 relationship between each other have a third table in the middle which contains some data, as if it was a many-to-many relationship. So to join two tables you need more JOINs than usual, and conditions on the third table's join
would be virtually the same as
public class Stats
{
public float _health;
}
in this case?
In practice yes, but it that is not the point I'm making it here.
omg, that's bad. Have they never heard of DB Normalization?
I see, yeah okay. You're correct, but for helping @fallow quartz they can just do what I wrote and it'll be fine no?
That was never the discussion. It was about whatever their professor are right to say that you should never use a public variable.
Like if one day you'd like to have an event raised or a method called when the value changes, you'd only modify the property's setter and nowhere else:
public int Sample
{
get => _sample;
set
{
_sample = value;
SampleChanged(); // new!
}
}
And you'd keep your c.Sample = 42; unmodified everywhere else.
If you didn't have the property, you'd need to add c.SampleChanged() everywhere you set a new value to c.Sample
well using serializefield makes sense so i can change the values through inspector
aha, my bad. I misunderstood the topic then :D
Using both makes no sense. It shows that you do not know what SerializeReference means.
how would u use that from another class? how would be the setter call?
so for this how can I usea Add method from Player and be able to change the variables value?
this is exactly the case with WPF, where you need a OnPropertyChanged event handler
It is a crucial part to make compositon base code. Which could be a way to architecture what you want.
The setter is called automatically when you set a new value.
c.Sample = 42; // setter is called (= 'c.Sample.set(42)')
Debug.Log(c.Sample); // getter is called (= 'c.Sample.get()')
so it's basically an anonymous function?
Yep properties are methods under the hood
The compiler makes the heavy lifting work
so in the IL, it will say "set()" and "get()"
Yup
but u must have a private value version of the attribute to use this or where else does _sample come from?
Yeah I omitted it in my example, but you need a field to back the property up
Unless you use an auto-property ({ get; set; }) in which the compiler creates that field for you
Next C# version will allow you to refer to the field directly, eliminating the need for a field when you have code in the accessors:
public string Name
{
get => field; // 'field' now a keyword referring to the compiler-generated field
set => SetField(ref _field, value);
}
For my WPF MVVM lovers
C#14?
I stopped counting but it should be in .NET 9 which releases next week-ish (?)
what a waste of space. even more bloat for a simple 'public string Name;'
well, we are stuck with Framework 4.7.1 until Unity 7
This notifies the UI the value changed so it redraws. Nowadays a source generator can hide that away from you
yeah but u get problems like the one from the Add method
but it hides nothing from IL which is what matters
that force u to make variable public
you need to notify XAML with the OnPropertyChanged(nameof(Name));
So, correct me if im wrong or missing something, but would this be the correct cheatsheet?
private GameObject _attributeA; //full private
public GameObject _attributeB { get; private set; } //readonly
[SerializeField] private GameObject _attributeC; //inspector serializable readonly
public GameObject AttributeC => _attributeC;
[field: SerializeField] public GameObject _attributeD { get; private set; } //inspector serializable readonly BEST PRACTICE
public GameObject AttributeE { get; set; } //full public
private int _attributeF; //full public BEST PRACTICE
public int AttributeF { get => _attributeF; set { _attributeF = value; Example(); } }
public class StatisticRepository
{
[SerializeReference] private List<Statistic> statistics;
public void Combine(StatisticRepository other) {...}
}
(If you have different type of statistics, other wise you can use [SerializeField])
A: Field, private
B: Property, read-only (outside of declaring type)
C1: Field, private (+ Unity recognizes the attribute so it's displayed in the Inspector - not base C#)
C2: Property, read-only
D: Property, read-only (outside of declaring type + marks the compiler-generated field with the attribute so it's displayed in the Inspector)
E: Property, public, read-write
F1: Field, private (backing field of F2)
F2: Property, public, with custom accessor logic
and with a bit of extra code you can enable init properties in Unity for some extra fun 😀
_XXX is used for private field usually.
[field: SerializeField] is not the best practice nor a bad one.
i just change my code on stats to use field: SerializeField and is not taking properly the values, everything is on 0
alright I got it, so this is the go-to or there is something I should change?
so is the one before that the right one regardless being longer and not being able to include custom logic?
you mean the old values disappear? even if the name appears the same in the editor, the name of the backing field unity is serializing for an auto-property is different to the old field so you'll need [FormerlySerializedAs] to make it upgrade smoothyl
Not sure what you mean. There is no "Right One".
Just need to adjust your terminology!
When it has accessors (get, set), it's a property.
When it doesn't, it's a field.
Attributes are the things you put in square brackets []. SerializeField is an attribute for example.
Each one is useful for different situations, but there is at least one that is overall better, like public GameObject AttributeE { get; set; } over public GameObject AttributeE;
In spanish we call fields "atributos" so I automatically call those attributes, my bad
I would say so. However, it is debatable.
Yeah in data modelling graphs these are also called attributes if I remember correctly
not necessarily, everything has a use! for example in that example you can't take the value of the property by reference, which could be useful in some niche cases
wdym? you cannot acces it from Class.AttributeE?
A structure by example.
public MyStruct PropertyA {get;set;} will return a copy of the structure.
you can't do ref AttributeE for a method that takes a ref parameter, if AttributeE is a property
Hence, you will not be able to modify it directly, you will need to set it back after you are done.
every value, the screen, the debug log and the values after scene changes
So one returns itself and the other returns a copy of itself essentialy?
kinda but to be pedantic fields don't "return" anything because they're not methods, they ARE the data
Yeah a reference is a "path" to the data, while a property is a copy of the data itself
But what im not getting is in which cases a field is initialized as one or another
no.
Property is something else. You have Reference Type and Value Type. If you return a value type it is a copy of the data, if you return a reference type it is a copy of the pointer towards the data.
If you use a property you "return" something. If you use a public field you access directly the data.
If a gameobject doesnt execute again Start when using dontdestroyonload, why my stats stay fine if I do it like in the image but reset if I declare it on the start? And whats the difference?
like here im getting it but where does the difference begin? declaring the variables?
Dude i know how to program and suddenly I feel stupid asf its like i have forgot the basics lmao
The difference is in the struct. If it is a class it is a reference type.
And the behavior differ
So it depends of the object type?
Yes
If you were to replace struct by class, you would not get the same result.
I understood here that it was dependant of how u declared the field
while you were talking about class types
yes, reference and value types are a different topic to what we were talking about
damn XD
One of those niche case is when you deal with value type
alr alr
so overall, outside of structs, enums and allat, everything else (classes, interfaces...) lets say the common stuff, should allow this without trouble
Thanks yall @steady moat@simple egret@thick terrace, I really appreciate your help! ^^
🫶
Why are you yelling?
and that is our problem why?
No
Sorry
I just wanted to share my suffering with someone
Does anyone know if its possible to resize a vertex buffer? I'm creating an empty max size vertex buffer to pass to a compute shader, but after i've generated these I'm almost always left with a lot of unused space at the end, any way to trim this out without copying a subset into another buffer?
Are state machines common for animations in 3D games?
If you mean Mecanim yes? That’s the standard Unity workflow
Doesn't seem like there's a way to do that aside from copying. Perhaps you should estimate the number of elements better when creating the buffer.
I don't know what I mean anymore omg. I was watching this tutorial to recreate genshin movement cause I thought I could build my knowledge from there but he's doing something I've never seen before
he creates these statemachine scripts and every single motion has it's own state machine which makes no sense to me cause normally, I thought we controlled them with variables in the animator tab
Then pooling the vertices seems like the way to go, thanks for the response though.
I just want to know how to properly animate a 3d character tbh
and adding complex motions to those characters
Statemachine behaviors are something you can attach to your states, generally useful when you need event when entering state etc. Animator params control transitions and some state properties like speed.
Read docs and try it out
where and how?
I did but I understand nothing that's why I'm here
Then start simpler. Research the things that you don't understand. Or at least explain what it is that you don't understand so that we can direct you to the proper learning resources
any good resource on humanoid character animation would be lovely
going simple from like walk and run to actions like swim, point and all
Well, that's a pretty simple thing to setup with the animator, so either look at the animator manual or search for some tutorials on YouTube or !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks
Hi so after updating my unity version, when I make new scripts, for a short time my console gets spammed with this message. Doesn't seem to be affecting anything in the game and it stops shortly after the script is created, give or take 3 seconds. I was wondering what this means and how to fix it!
How do I fix this error?
looks like a synchronization delay between os time scale and given time scale. try deleting your library folder and seeing if that helps
what is that script attached to
Its just the defualt global light 2
Im creating a 2d multiplayer game with FOW and imported this data
am I missing a setting to enable?
sorry im not very familiar with 2d so im not sure
but this question would be more suited for #💻┃unity-talk
try asking there
I'm trying to make a healing beam similar to mercy from Overwatch does anyone know how to make the line renderer curve when the direction of the healing staff is facing a different direction than the target? Or if their is a better way to make this than a line renderer?
probably some type of shader? maybe a spline mesh on it w shader ?
more of a #✨┃vfx-and-particles / #archived-shaders question i think
ok I didn't know if their was any way to do it with code with the line renderers points and just wanted to check
I would honestly use a spline type deal with a shader, or the shader itself can just create that curve effect instead of bending the mesh
with code you would probably need to use bezier curves and line renderer or something
btw found these https://youtu.be/R0A0rWljTm4
https://youtu.be/NMAAeGiEHwk might help out if you go in the VFX route
Use a Bézier curve
yeah the bezier curve works thanks!
Has anyone here integrated the SteamUtils API in their code?
Kind of confused -- I'm not sure how to A) check if the user has pressed the "submit" button and
B) How can we get the entered text?
this is my code if it helps =--
using UnityEngine;
using Steamworks;
using TMPro;
using System.Collections;
public class SteamDeckVirtualKeyboard : MonoBehaviour
{
public TMP_InputField inputField;
public string promptText = "Please enter text";
public int maxCharLimit = 300; //max char limit for input
private void Start()
{
if (SteamManager.Initialized)
{
inputField.onSelect.AddListener(ShowVirtualKeyboard);
}
}
private void ShowVirtualKeyboard(string selected)
{
// Check if the game is running on a Steam Deck
if (SteamManager.Initialized)
{
Debug.Log("IS RUNNING ON STEAM DECK");
bool isShowing = SteamUtils.ShowGamepadTextInput(
EGamepadTextInputMode.k_EGamepadTextInputModeNormal,
EGamepadTextInputLineMode.k_EGamepadTextInputLineModeSingleLine,
promptText,
(uint)maxCharLimit,
inputField.text
);
if (isShowing)
{
// Start the coroutine to check for text submission
StartCoroutine(CheckForSubmit());
}
}
else
{
Debug.Log("NOT RUNNING ON STEAM DECK");
}
}
private IEnumerator CheckForSubmit()
{
// Wait until the overlay (virtual keyboard) is closed
while (SteamUtils.IsOverlayEnabled())
{
yield return null;
}
// After the overlay is closed, retrieve the text
string enteredText;
uint bufferSize = (uint)maxCharLimit;
bool success = SteamUtils.GetEnteredGamepadTextInput(out enteredText, bufferSize);
if (success)
{
Debug.Log("ENTERED TEXT: " + enteredText);
inputField.text = enteredText;
}
else
{
Debug.LogWarning("Failed to retrieve entered text from the virtual keyboard.");
}
}
}
It looks like the "enteredText" is empty
I basically just want to get whatever text is inside the box that pops up -- whether the user modified it or not through the virtual keyboard -- and make that the "enteredText"
I believe you should call that method only within GamepadTextInputDismissed_t callback.
The struct also contains if user submitted or not
how does one un-unpack a prefab
If a prefab is unpacked in a scene, you cant re-pack it unless you Ctrl + Z and undo the operation, otherwise it would be easier to just drag another prefab into the scene again, unless your wanting to make a prefab variant
hey, a question: does unity support auto-tiling at runtime, or would I have to implement that system myself?
Hi. I get an error that says "Layer index out of bounds" when I'm trying to log the layer name. What can cause this?
var context = ActorContext.Context;
Vector3 origin = context.transform.position;
Vector3 direction = -context.transform.up;
Ray ray = new Ray(origin, direction);
Document doc = SonicGameDocument.GetDocument("Sonic");
ParameterGroup group = doc.GetGroup(SonicGameDocument.CastGroup);
float castDistance = group.GetParameter<float>(Cast_Distance);
LayerMask mask = group.GetParameter<LayerMask>(Cast_RailMask);
Debug.Log(LayerMask.LayerToName(mask));
LayerToName takes a Layer ID not a LayerMask
Don't use it.
it's too late i already invested 10 years into this bullshit
10 years and you still dont know how to use it properly, shame on you
Doing what? How is supposed to look(and where)?
Well, why would it not be? What is there to make it look correctly?
ok you're trolling
No, I'm trying to drag more details out of you. Otherwise it's impossible to help you.
Yes, that much I figured out. I'm asking why it shouldn't be? What are you using to make it look orderly as you expect?
it looks fine before i press play
scene view
then it gets all fucked up after i play
Take a screenshot
I really hate making assumptions, but I guess you're using bone animations or something. The fact that it breaks at runtime means that there is an issue with your rig setup or animations.
ah my animation
You also have a null ref exception in your console which may have something to do with it
If I have this inheritance hierarchy and there is a same variable on those 2 classes, is there any way to avoid duplication?
Pull it out into a base class.
Make these 2 child classes inherit from an intermediate class that has the field.
but the variables in the parents of this 2 classes are not the same
im going to make 1 full class just for 1 variable?
imagine this for each variable thats shared
would be crazy
Not advisable. This might point that there is an issue with your design. Maybe you should be using composition more and inheritance less.
If you give an actual real life example of your issue, it might be easier to provide a suggestion.
is there more "tools" apart from inheritance and compositions for this type of stuff?
so how do I get a good design
There are all kinds of design patterns, but it's hard to say what would fit here without knowing the context.
bump
tiling what exactly, a background or actual tiles?
i wanted to make a destructible 2d environment
the idea is that you mine tiles for gold
and I was wondering if auto-tile at runtime is supported
yeah i don't think something like that would be implemented
too many specific details to make a general solution
ffs
not too hard to make though
yeah, specific systems are like that
is it so specific though?
you already can define rules for tiles
in editor, at least
if they were able to make it work in the editor it seems weird it doesn't at runtime
I have no real experience using tiles so I might just be outright wrong though
- what range? (camera edge or distance from player)
- what tileset? (maybe weighted, maybe depends on some different variable)
- what is replaceable?
your answers to these create a specific system
- aren't tiles just placed based on a grid? distance/camera has nothing to do here
- don't exactly know what you mean here
- you can replace any tile at runtime, so I don't see how that matters
aren't rule tiles just.. tiles with specific behavior
they don't create new tiles, they just modify existing ones
- conceptually, yes, but you can't generate infinitely. you have to decide when to start generating.
- what tile(s) should be used when generating new areas? how are they weighted? for example, if there's a concept of depth, then maybe that affects what tiles spawn, or the weight in which different kinds are chosen
- i mean, within the system. what tile should be replaced? you shouldn't generate stuff over existing tiles, or that would just close up anything you destroy
Hi,
Is it possible to make a specific camera not render the environmental lighting?
I'm not generating anything at the moment, for now I wanted to just remove a tile and see if surrounding ones "adapt" at runtime, nothing fancy...
nevermind
oh, i have severely misunderstood what you meant by "auto-tile" lmao
for that yeah pretty sure rule tiles work at runtime
great, that's what I wanted to know, thanks
In Unity, is there a way to automate the declaration of properties by composition?
For example. If I put a tag [RequireComponent(typeof(DoorBehaviour))], a DoorBehaviour _doorBehaviour property is automatically created, and also _doorBehaviour= GetComponent<DoorBehaviour>(); is added to the existing Awake() or a new generatedAwake if not implemented yet?
on classes but yeah
it automatically puts the desired behaviour into the gameObject but u must do it from a script with class
Can someone help me with the last question in that thread pls? Idk why when initializing the stats on start they are at 0 all the time but if I do It outside or on awake it works properly
does the object implement the singleton pattern?
no, its just a sphere with the player script inside
So... Is there another copy in the scene you're loading?
of the sphere? No, its the only one
then when the scene reloads a new version will be created and Start will run on that
But you're reloading the same scene, no?
another one
im not reloading, its going into a new scene
Which scene are you loading and what's in the new scene
im in a UI menu, I choose the race, class and weapon, then i confirm with the button, goes into another scene and the sphere appears on top of a cube with that script
Start will not run on a DDOL object after it is first created, so no it will not run again
so why is this happening then?
almost certainly you are misinterpreting what you are seeing. Debug the Start method if you think it's running twice
I made a debug log and the stats are at 0 even in the scene before, so i dont think the problem is DDOL
Debug.Log(playerInstance.GetComponent<Player>().Race.Stats.Hp);
Debug.Log(playerInstance.GetComponent<Player>().Race.Stats.PhysicalDamage);
I added this 2 lines just right under BuildPlayer has been executed
and they are on 0 but the object has the stats on the next scene
i have a sprite sheet for animation
but i cant drag it into the scene
i can only drag it under another object
and it doesnt show it
nvm
solved it
@knotty sun @leaden ice
public void ConfirmSelection()
{
GameObject playerInstance = Instantiate(playerPrefab);
CharacterRaceTemplate selectedRace = GetSelectedRace();
CharacterClassTemplate selectedClass = GetSelectedClass();
WeaponTemplate selectedWeapon = GetSelectedWeapon();
ArmourTemplate selectedArmour = GetSelectedArmour();
TrinketTemplate selectedTrinket = GetSelectedTrinket();
Player playerScript = playerInstance.GetComponent<Player>();
if (playerScript != null)
{
playerScript.BuildPlayer(selectedRace, selectedClass, selectedWeapon, selectedArmour, selectedTrinket, "YOU YOU");
Debug.Log(selectedRace.Stats.Hp);
Debug.Log(selectedRace.Stats.PhysicalDamage);
Debug.Log(playerInstance.GetComponent<Player>().Stats.Hp);
Debug.Log(playerInstance.GetComponent<Player>().Stats.PhysicalDamage);
}
DontDestroyOnLoad(playerInstance);
//SceneManager.LoadScene("Test");
//Debug.Log("Character with: " + selectedRace + selectedClass + selectedWeapon + selectedArmour + selectedTrinket);
}```
the issue could be that when i instantiate the object start is not running right there?
Start will run if the Object and the script are active/enabled AFTER all of that code is finished
and why is not running as soon as is instantiated?
because your code is still running. Only Awake is guaranteed to run when Instantiate is called
yeah then thats why it works in Awake and not Start
If I do it like this, when are stats initializing? Before Awake?
public abstract class Entity : MonoBehaviour
{
[SerializeField] protected string _name;
[SerializeField] protected Stats _stats = new Stats(0, 0, 0, 0f, 0f, 0, 0, 0f);
protected virtual void Start()
{
}
protected virtual void Update()
{
}
}```
Why is https://docs.unity3d.com/2022.3/Documentation/Manual/UIE-Pointer-Events.html
Missing IPointerExitHandler?
Which pointer events do I need in order to replicate button hover states to change color?(I need this specifically to change color of text based on a pointer state)
Unusual construction. Obviously as an abstract class that is never initialized
but imagine I put values and is not 0, 0, 0, 0
like when is that being initialized? cause in unity u can see the values
if you are talking about a class inheriting from that then the serialized values are set before Awake
and in this class in particular its also before awake?
no, as I said, it's an abstract class so can never be instanced
well imagine is not abstract
public class Player: MonoBehaviour
{
[SerializeField] protected string _name;
[SerializeField] protected Stats _stats = new Stats(0, 0, 0, 0f, 0f, 0, 0, 0f);
protected virtual void Start()
{
}
protected virtual void Update()
{
}
}```
its just to know the theory of how it works
then what I said above is true, deserialization takes place after instancing and before Awake
Okay, and for this particular case where i want a gameobject to get the stats from templates (SO), is it better to move the initialization of stats from entity to Awake or where it is or leave them on the start and just create a gameobject right instant before the method executes? (which is really annoying, I thought instantiate would instantly activate start and trigger before the whole method finishes)
best, if you want instant access to the variables is to set them in Awake, that way you will know they will always be avaialble
Perfect, thanks so much ❤️
Hello, does anybody know if there any way to avoid having to move every reference in the inspector after you change variable names? Its really annoying when you have a lot of references or even lists. I also find quite unpleasant doing it by code through FindByName.
Hello, having some issues with event triggers not triggering
When you design a inheritance hierarchy is it more efficient to start building from the childs onto the fathers or from the base class into the childs?
Hey guys any ideas why this FPS displacement script works on editor but not on build?
{
public TMP_Text fpsDisplay; // Reference to a UI Text component to display FPS
private float deltaTime = 0.0f;
void Update()
{
deltaTime += (Time.deltaTime - deltaTime) * 0.1f;
float fps = 1.0f / deltaTime;
// Update the Text component with the FPS value, rounded to whole number
fpsDisplay.text = "Current FPS: " + Mathf.Ceil(fps).ToString() ;
}
}```
in what way is not working?
FormerlySerializedAs?
how does that work
when you rename a field put that attribute on it to tell the serializer the old name, it'll keep the old value and save it under the new name the next time the asset is saved
so you can remove the attribute later if you're sure all the assets have been resaved
Ill check it out, thanks brother!
well when I play the game in the editor I see it updating the text according to the fps, but when I build the game it gets a static number, meaning that its not updating the text tho for some reason, asked chatgpt and it said it might be due to textmeshpro, but also no alternatives were said to solve it.
that is expected, gpt is text conversation machine, its not a thinking machine
anyway make a dev build and check for any null references on screen or in the PlayerLog file, also double check you are exporting the correct scene
loved the gpt tea! Well will try that thank you 🙂
I have this prefab which I instantiate at a certain point in my game, and to which I attach through code an event trigger. Still through code I add a method as a listener.
This is the code that adds the method as a listener:
[HideInInspector] public UnityEvent onClick = new UnityEvent();
private EventTrigger eventTrigger;
private void Start(){
eventTrigger = GetComponent<EventTrigger>();
EventTrigger.Entry clickEvent = new EventTrigger.Entry()
{
eventID = EventTriggerType.PointerDown
};
clickEvent.callback.AddListener(OnClick);
eventTrigger.triggers.Add(clickEvent);
}
private void OnClick(BaseEventData shit){
Debug.Log("AAAAA");
onClick?.Invoke();
}
The event system is in the hierarchy, and the object presents nothing but an image component and the component itself
Why make a UnityEvent just to hide it in the inspector and use an event trigger instead?
as I don't wanna go through the hassle of handling a collider in there
ok, maybe I have explained my self poorly
If it's not a UI element it needs a collider for On click to work
As well as a physics raycaster on your camera
If it's UI it needs to be on a canvas and have a Graphic component and you need a graphic raycaster on the canvas
But this business with the extra UnityEvent is definitely not necessary in any case, it's a bit wasteful
You can also just implement IPointerClickHandler directly and avoid the event trigger entirely
How do I make it so that the press of a button, through a second camera, with its feed displayed on an object through a render texture, is registered?
when I say button I mean an UI element
in world space
You'd need to make a custom raycaster that translates the click from the Raw image component to another event system Raycast in world space for that to work
I see
Assuming you're using RawImage
If it's a mesh displaying the RT you need a physics Raycast first
I'm doing this, so yeah
so i first translate the mouse movement from the main camera's space to the second one's and then what?
No first you do a physics Raycast to the mesh. Use the texture coordinate from the hit to figure out where on the second camera to fire a second Raycast from your Graphic Raycaster on that camera from
Ideally you'd do this
In a custom event system raycaster
Because then it will work with Event Trigger
If i need to make a CD for an ability is better to use coroutines or just use a variable with time.deltatime?
whats more efficient
ok, thanks
It will always be a little bit efficient to check a boolean in Update rather than add an additional Coroutine, which is called at the end of the Update method. However, the difference is really small, and, in my opinion, it's more readable for you to use a Coroutine
Efficiency should not be your primary concern at this point.
Readability and code architecture should be
Hi! I have a question regarding performance. Is there a difference in performance in these two lines, and if so, why? They both give the same result, but if one is faster I will use that.
int x = a+b*c-b;``` vs
```cs
int x = a+(c-1)*b```
It's the same number of operations
and even if it wasn't this would be the very very least of your performance concerns in a unity game haha
Indeed
Assuming these are all ints at least
Also assuming none of them are properties
If b is a property it would be different
Or function call
Personally, I do not really like the usage of Coroutine in that context. I tends to use a startedAt value.
Something like:
private float startedAt;
public void Use()
{
startedAt = Time.time;
}
public float RemainingCooldown() => Cooldown - (Time.time - startedAt)
shouldnt i use time.deltatime?
i thought it was better
What is a "property" in this context?
Why ? If you do not need to count the time, do not.
Do you count every minute you are alive to keep track of how much time you have been alive ?
Thanks. So getting a property of a different class is slower than getting a property from the same class?
Or is it always slower getting a property of a class than getting a variable within the method?
no
properties work more like methods. fields are always "faster"
fields are generally direct access to memory, method has to create a stack allocation
Still not 100% sure what the difference between fields and properties are 🤔
best to look them up. Field is generally when you create the variable like
private int myField
property always have accessor public int MyProperty {get; set;} // <-accessor
Ah, okay! Thank you for explaining it 😊
when you get value run this function
when you set run this function
and you can specify what to do on each one with a function
Hi, is there any way to increase the NavMeshAgents priority level above 99? I need it for making an RTS with hundreds or thousands of units on screen. I want to use it to make units not overlap in various situations. 100 positions is also very bizarre, it's and Integer, so why only 100 values?
I have made various systems such as moving in formations or keeping group shapes, moving around corners with a random distance for big groups, etc...
But it's still not enough. For example a group of units attacking a single unit ends up having all units overlap pretty hard. If units that are closer to the target had a higher priority, it would reduce the overlap significantly. But I need to have 100.000 to 1.000.000 priority levels to achieve this.
Thanks for your time!
dont cross post
Ok sry I wasnt sure which of the two channels to post it to so I did both just in case
No. Calling a property is the same as calling a method/function, so fewer of them is better
Ahh!! Thank you so much! This is pretty helpful actually -- so something along the lines of this from what I'm gathering:
using UnityEngine;
using Steamworks;
using TMPro;
using System.Collections;
public class SteamDeckVirtualKeyboard : MonoBehaviour
{
public TMP_InputField inputField;
public string promptText = "Please enter text";
public int maxCharLimit = 300;
private Callback<GameOverlayActivated_t> overlayActivatedCallback;
private void Start()
{
if (SteamManager.Initialized)
{
inputField.onSelect.AddListener(ShowVirtualKeyboard);
overlayActivatedCallback = Callback<GameOverlayActivated_t>.Create(OnOverlayActivated);
}
}
private void ShowVirtualKeyboard(string selected)
{
if (SteamUtils.IsSteamRunningOnSteamDeck())
{
Debug.Log("IS RUNNING ON STEAM DECK");
bool isShowing = SteamUtils.ShowGamepadTextInput(
EGamepadTextInputMode.k_EGamepadTextInputModeNormal,
EGamepadTextInputLineMode.k_EGamepadTextInputLineModeSingleLine,
promptText,
(uint)maxCharLimit,
inputField.text
);
if (isShowing)
{
StartCoroutine(CheckForSubmit());
}
}
else
{
Debug.Log("NOT RUNNING ON STEAM DECK");
}
}
private void OnOverlayActivated(GameOverlayActivated_t callbackData)
{
bool isGuideVisible = callbackData.m_bActive == 1;
if (!isGuideVisible)
{
StartCoroutine(CheckForSubmit());
}
}
private IEnumerator CheckForSubmit()
{
string enteredText;
uint bufferSize = (uint)maxCharLimit;
bool success = SteamUtils.GetEnteredGamepadTextInput(out enteredText, bufferSize);
if (success)
{
Debug.Log("ENTERED TEXT: " + enteredText);
inputField.text = enteredText;
}
else
{
//fail print
}
yield return null;
}
}
is there any reasonable way to search for text across all of the user-made scripts in my project? it would be in any .cs files in Assets/_Project. I want to search for the number "204" as i want to swap it out to a variable rather than hard-coded number
Hi! I am overwriting a texture with Texture2D.SetPixel(), and then calling Texture2D.Apply(). After running the script, it shows the old texture when I open the png file in another program. How do I make it show the new texture instead?
Are you saving the texture?
byte[] pngData = texture.EncodeToPNG();
if (pngData != null)
{
File.WriteAllBytes("path/to/your/texture.png", pngData);
}```
No, I didn't know I had to. Thank you 🙏 Is there a way to get the path from the Texture2D? Something like texture.path?
you cant get it directly from the texture2d that i know of.
if you are getting the original image through code then maybe you could store that path?
i pasted exactly what you asked in to GPT and it told me that lol
Alright, thank you
I'm not really confident that GPT knows what's right. I could be wrong 🤷♂️
gpt only knows what the internet knows
so it most likely took that from stackoverflow or some other site
"path/to/your/texture.png"? What is the origin folder?
Do I have to right "C:/...", or is it already in the folder that the script is in? Or the asset folder?
i believe it's the exact path with C:/... though i think there are variables to get certain paths
like filePath = Application.persistentDataPath + Path.AltDirectorySeparatorChar + "data.json"
which will be in your Appdata LocalLow
generally with "simpler" things gpt is solid. especially now with 4o/4o mini. definitely good to double check it's work though if you're not sure, and make sure to understand all the code ofc
Generally you would use Path.Combine to create path strings
oh so i dont need that separator char? like filePath = Path.Combine(Application.persistentDataPath, "data.json") ?
nope
nope you dont need the seperator
sick. that excerpt would be a proper replacement then?
yes
sweet. ill keep that in mind in the future
Does anyone know a way to see all forces applied to a specific rigidbody?
I am having troubles with a CarController where I let go of gas pedal and car continues to accelerate for an amount of time. time it accelerates for scales with the speed of the vehicle when i let go of gas pedal. i want to ensure there is not some random script somewhere affecting that rigidbody.
In my Update() i have throttleInput = Input.GetKey(KeyCode.W) ? 1 : 0;
and in FixedUpdate() i have
{
rlWheelCollider.motorTorque = 2000;
rrWheelCollider.motorTorque = 2000;
} else {
rlWheelCollider.motorTorque = 0;
rrWheelCollider.motorTorque = 0;
}```
I have made **certain** that `throttleInput` and `motorTorque` work exactly as they should by using a Debug.Log. I have disabled everything else in this script, and know for a fact that the other two scripts on the vehicle do not deal with movement in any way. vehicle has a custom mesh collider and rigid body, children wheels have the wheel colliders.
Does anyone know a way to see all forces applied to a specific rigidbody?
rigidbody.velocity. That's the result of all forces on the object.
I mean to see if there is some random script somewhere applying forces. I don't think rb.velocity is what I'm looking for because i can see that the vehicle is moving
I believe its called Rigidbody.linearVelocity now
I'm moreso asking about finding sources of velocity, not seeing the actual velocity of the vehicle. I have an onscreen Km/h for that 🙂
sources of velocity, elaborate.
I have looked at all references to the gameobject that has the rigidbody and none of the scripts on those objects add forces
do you have any physics materials on your car, do you have friction on your car?
do you have raycast suspension?
Well you see the code snippet I offered above, so you would expect that when I let go of W and motor torque is set to 0 (i know for certain it goes to 0), that the vehicle would decelerate or at worse stay the same speed, however it continues to accelerate
i only had the keypress and the motor torque code enabled on the script. anything else would come from the wheel collider or rigidbody
oh whhops i didn't open the dropdowns
@spare dome do any of these values jump out as wrong?
does it keep accelerating forever after input or accelerates longer after you stopped the input then stops after a while?
stops after a while. the faster i am going when i let go of W the longer it will take to stop accelerating
does it stop accelerating after a second or two then starts to slow down?
yeah
Should be able to right click the rigidbody or the gameobject and click find all references (or whatever the option is called)
if im going like 15kph and let go it gets to like 25, but if im at 100kph it will go to like 200 or so
even though motor torque is def set to 0 on the wheels
did try that, looked at all scripts on all game objects that referenced it. did not find anything
and yes it slows down normally once it stops accelerating
try 1 - 5 to see what works if at all
setting drag to 1 using 5000 motor torque on back wheels lets me get to 19kph 😛 doesnt fix issue though :/ i let go at 5kph and still goes to 19
drag at .1 still same accel issue but i can go higher speed 😦
I'm trying to create a display for a sort of movement area for a character (That is the maximum distance a character can move in one turn) and I want to omit the vertices outlined in green from the final mesh. While I know how to find what vertices should be omitted, I don't know how I would go about drawing the triangles for these meshes let alone in a way that only omits the areas outlined in green. Any ideas?
One thing that seems suspicious is that the rb is kinematic? I don't think it's supposed to be kinematic for a setup with wheel colliders. Or are you changing that via code?
What is the purpose here? To prevent these vertices from being rendered?
yeah it's kinematic until the car is finished being set up
More to prevent that entire area of the decal (that's what I'm using to display the area) from rendering. I know how to find the vertices I need to exclude, but I don't know how to draw the mesh with the remaining vertices so that the area displays properly
is there a way to put 3d models in while the unity game is running i think we can use addressables no?
Okay.
I think wheel colliders have something like inertia, where even if the motor torque is set to 0, they would keep on applying forces depending on their rotation speed and other parameters. I think wheel damping is meant to control that. Can you try setting a higher value for wheel damping?
If it's simply for rendering purposes, it might be easier to set it up via shaders, with stencil buffer checks for example.
I barely know how to even use shader graph. Unless that's possible with shader graph there's no way I can do that
It should be possible with shader graph and/or render features(if using urp).
dang, all that did was make the vehicle accelerate slower and decelerate quicker. the issue persists unfortunately 😦
Any resources on how I can do that then?
Maybe look up tutorials on masking geometry with stencil buffer in urp.
ok so I'm trying to get an object to move from one side of an object to another this is what I got but once it gets to one side it stops and gets stuck, I realized it was because it would play both if statements at the same time. I can't figure out how to fix this and going on google hasn't been helpful. I tried using while loops so that the if would play until it gets to one side but learned that causes unity to freeze up so I don't know what to do.
Think about your code
it doesn't make sense
it's trying to determine which way the object should move solely based on its current position
Think about whether that's actually enough information to determine which way it should be moving.
(it isn't)
FOr eample, if the object is currently in the middle should it be moving left or right?
idk but its for a school assignment where I have to build off my professor's code. This is what I'm working with
You don't know?
THink about it
Use your brain
tell me if you think you can tell based on just the position
depends on which way its currently running
exactly
So you need to keep track of that
How do you keep track of things in a computer program?
Think about how you might do that
using variables
ding ding ding
so what kind of variable could you use to track which direction the object is currently moving?
Well you could do that but isn't there a better type to keep track of something that can only have two possibilities?
So then - use a bool variable and then think about what the code should look like given there are two possible modes for your object and values for that variable
think about it like:
- If the object is moving right, then we are looking for a certain condition to turn around
- otherwise, we're looking for some other condition to turn around
and also - the movement needs to change based on the bool as well
== to compare
you're doing = which is assigning the bool
but also you never need == true or == false
you should just do:
if (moveLeft) {
// is moving left
}
else {
// is moving right
}```
and you are always assigning moveleft to true because it is in update
this too
oh yeah I always forget that 😭
use Start for things that should happen only at the beginning
yeah I caught that right after sending the screenshot
alr fixed it up and now its working thanks a lot for the help
also since you are basing it off of the position, it would only work if the object is at the world origin (0,0,0) so if you want it to move around to different places I do not think it would work, so you could do something like this if you want
offsetposition = new vector3(0,0,0);
currentpos = transform.position + offsetposition;
if(currentpos.x >= offsetposition.x + 4){
// do something;
}
now I have no idea if this works but you get what its trying to convey
Stop what you're doing and configure your !ide. There is no point in working on a project when your editor is not working correctly.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
@cosmic rain @spare dome My issue with accelerating seems to be more or less solved when I set the mass of each wheel to .1. I will have to look in to why this is the solution because there may be some other underlying issue
I have an FBX file with several animations in it, and I'm importing those (Legacy) animations with the 3d model. In-game, I load in the the 3d model as an addressable. Does this also load in the animations that were imported with the model? Or do I need to load the animations as a separate addressable file?
What exactly are you loading when you load the 3d model
A prefab?
A Mesh?
A prefab, yes
A prefab with an Animator?
Whatever is directly referenced in the prefab will be loaded with it. If it has an Animator with the animations, it will load that.
No, there was an Animator before, but I removed it. You were helping me with that problem yesterday. Essentially I have hundreds of animations in one fbx file. Loading all the animations in the Animator was taking up a ton of memory.
I managed to replace the Animator with an Animation component by importing the animations as Legacy animations.
The memory use went down significantly. But now I need a way to fetch the one specific animation I want (via script) and play it with the Animation component.
Make it addressable or use resources
Make each animation clip an addressable?
When I run the profiler while loading in the prefab, the profiler is still showing hundreds of animation clips (even though the memory use for them is lower). So I thought maybe those clips were being loaded in with the 3d model in the prefab.
Hey, kind of a weird question, but has anyone made a Task<bool> that returns true if a specfic event has been called in a timeout period, else returns false?
Guys an asset throw Editor errors from Editor folder when i try to compile. what to do
i guess if theres at least one assembly then unity will try to compile Editor folders when building the client.
i'm guessing the answer is yes that has probably happened at least once in history, but did you have a specific question 😛
I would have never guessed the wheel mass, well I'm glad it works
got lucky with a unity thread that had the exact same issue. not sure why that happens though. i do remember in a previous vehicle-based project that my wheel mass was like 20kg or something and it was fine
wouldn't it just be something like (psuedocode):
bool eventHasRun;
Action listener = _ => eventHasRun = true;
myEvent += listener;
float timeElapsed = 0;
while (timeElapsed < timeout) {
timeElapsed += Time.deltaTime;
if (eventHasRun) {
myEvent -= listener;
return true;
}
wait one frame
}
myEvent -= listener;
return false;```
the only concern is that if you call the function by its name instead of invoking the listener then it won't trigger eventHasRun
only would happen if someone was using your code
There is no way to "invoke the event by its name" without triggering the listeners
if you mean some specific listgener function then sure but then we're not talking about an event anymore
unless I'm misunderstanding you
GUYS if framerate breaks/lags is there a way to log real life time somehow via code since game start that has passed
like i want to know if my app took 1min or 3min to finish loading (low framerate during loading, making it hard to count time)
Thanks senpai
Hey there. I have a scene where I have a video capture from a we came going in and rendering on a rawimage under a canvas.
The user can then choose to put an overlay ontop of this via a selection keypress.
The overlays are png sequences as they are animated and have transparency. I'm currently going through the png sequence in the update, there is probably a much better way to animate the png sequence, but I havn't gone down other paths yet.
The user can then start a recording.
Currently I have a camera that is rendering to a rendertexture and then I saving each frame of the render texture, then stitching with ffmpeg to get an mp4.
The problem I'm having is thst the saving of each frame is causing the video on screen to lag.
Is there a good way to move like the saving of the images to another thread or to a buffer or something instead of direct to file,
blit the texture to a buffer (array or list of textures) https://docs.unity3d.com/ScriptReference/Graphics.Blit.html
as for the actual saving part, or saving.manipulating textures in another thread, I'm not sure about
I'll check that out, thanks
Instead of using inheritance for avoiding variable duplicate, is it a bad or good practice to for example in a class stats put all the stats of ur game and just make 1 constructor for each case? With this strat you can just build stats and the class will use only the ones needed
And is there any similar way to do this with methods?
Why is it that having an Animator with 100s of states for different animation clips takes more memory that storing those same animation clips into a serialised list on a game object? Wouldn't the same information be held in memory in both cases?
what's wrong with using inheritance? Adding a lot of unused variables is not normal - you can use components also as Unity does but inheritance is classic C#
Didn't we go through a whole discussion last week about this?
The answer is composition
This conversation #archived-code-general message
Not really. At least, not in a game with an extensive statistic needs.
That being said, it could potentially be done in case of statistic modifier (percentage_damage, flat_damage, percentage_damage_versus_weak), etc. But in case of Base Statistic, it simply does not work as you might have multiple statistic of each type.
I would not define attributes with string names and values - that is troublesome - the magic string situation. You can use both composition and inheritance but don't abandon inheritance
It's not a magic string situation
you can use an enum if you want, or define constants
guys so im in loading screen and i have no idea how quickly i can execute code. cause people are going to have slowe rmachines than me lol
this was a quick and dirty solution to explain composition
ok I see - yes enum perhaps. I have not not gone that far with composition but it is an interesting plan. But you need a lot of code to check the attributes listed and do different work accordingly, which might be easier just using inheritance
not a lot of work really
each ability function handles its own
inheritance simply does not solve the problem
and as soon as you encounter a case where inheritance doesn't fit, you have to tear the whole system down
I guess it is a bit like the component pattern - if they can all work individually its great - if they end up having to reference each other it gets complex
yes _comp_onent systems are a form of _comp_osition
and how do you fix this if it happens
I would have to look at a full example of composition - I have not struggled with inheritance before though
you tear the whole system down and built it differently. My recommendation is using a composition structure
is inheritance bad
inheritance is not bad
it's a tool
that can be misused
like any tool
it has its place
composition makes me think of a game where you can add components to a robot until it does what you want. It could make a good game somehow! It definitely has a good feel, but you gotta try all tools until you find what works for you
People tend to learn polymorphism/inheritance when learning OOP and then think it's a cure-all solution for every single class of problem and that is just not what it is.
there are many ways to change a light bulb
actually not really - but something something ways to do something
Huh? My editor is working fine
Your screenshot suggests otherwise
No highlighting says enough here
Highlighting for what specifically
Cause it does do highlighting for all instances of a certain variable when one is selected
It's probably fine - just reopen VS by closing it then opening it within unity by double clicking a script file in the project - might have to kick unity to regenerate the project/solution files
Debug.Log() for example
transform in transform.Translate should be highlighted, Translate() should too.. your ide isn't recognizing those members
Why would it be highlighted I only have Vector3 selected
by "highlighted" we mean "colored"
syntax highlighting is highlighting different syntax elements by coloring them
like namespaces and types should be green in your current theme, but only sphereMove is in your screenshot
Ohhhh yeah I gotcha now
so what's the proper way to move rigidbodies? MoveRigidbody glitches on collisions, just setting velocity ignores all other forces. Maybe adding to velocity and then checking if magnitude is not over a certain threshold?
AddForce
MovePosition ignore collisions because its meant to kinematic
Doesn't add force stack? The same issue as with velocity, I can't keep adding or setting it, because i want constant speed
constantly checking if the speed is above a certain threshold seems excessive
oh yeah true, in that case something like a V3/Vel clamp above a threshold. afaik thats the only way
You can do exactly same as with .velocity with AddForce alone if you just calculate the required force correctly. Calculating the force yourself may give you more freedom to do custom stuff though hence AddForce is often preferred
//move input
var sqMag = rb.velocity.sqrMagnitude
if(sqrMag * sqrMag > maxSpeed)
rb.velocity = vector3.ClampMagnitude(rb.velocty, maxSpeed)
else
rb.AddForce
Vector3.ClampMagnitude exists btw
ahh wops
if i declare in an abstract class a dictionary and then 2 classes inherit from it, the classes will have the dictionary empty so i can fill it as i want right?
so like this I have full control over what variables i want in a class, s that correct?
or is it a bad implementation
All you've mentioned was a dictionary in a base class, we dont have much context as to what you'll use this for
im just thinking other ways of building the stats/ability system
why not just make a class that has a Dictionary as a field, instead of deriving from Dictionary
thats what i said?
yeah me 2 i had to read twice hahaha
But it's not clear what you're gaining from the abstract class here.
well with this system i dont have to build up a full inheritance tree for abilities sharing variables
Right that's what the Dictionary gets you
cause the dictionary is empty, i just put <Stat, float> (Stat is an enum with all the names) and then i can fill it on each class
ability class i mean
what does the abstract class get you
all the abilities inhertir from the abstract class
so they all have the dictionary
otherwise i have to declare them in each class
but why do they need to be different classes at all
each skill does something different and has methods
how would u approach it then
and place the methods on separate classes? or wdym
well with a delegate you could put them... anywhere you want
its fine though
your approach is fine. It's very similar to the List<Attribute> approach I mentioned
Can static values be set like any normal value or do they reset after the next call?
you mean variables and they are normal variables
not sure why you have the impression they would reset at some point.
Well I just thought, because they were static
Static means they are not attached to an instance of a type.
It has nothing to do with "resetting"
whatever that means
like turning it back to false for example
is it possible to replicate this but without using a dictionary? And btw the similar thing with methods is what u said about delegates?
But thanks
Even in my List<Attribute> case, at runtime often I would build a dictionary in order to acces the attributes efficiently
does anybody know is possible to avoid the header cloning when declaring fields in a single line?
[Header("Config")]
[SerializeField] private float _lookSensitivity, _walkSpeed, _gravityMultiplier, _jumpForce, _dashForce, _dashDuration, _dashFovChange, _dashCooldown;
don't declare the fields on a single line like that. what's happening is the attributes are applied to each field declaration on that line, which means the Header attribute is applied for each of them
It's not.
[Header("Config")]
[SerializeField] private float _lookSensitivity;
[SerializeField] private float _walkSpeed, _gravityMultiplier, _jumpForce, _dashForce, _dashDuration, _dashFovChange, _dashCooldown;```
That being said, you could create your own property drawer and handle that case.
how in earth?
how does that even work XDDD
ye ye i just tried it works but why does it now detect each field in the single line as a different one and it didnt b4
😵
it's doing exactly the same as what you just had
the only difference is Look Sensitivity was pulled out into its own group with the Header attribute
Didnt know, anyways, I appreciate the help!
as i described before, when you attach an attribute to a line of field declarations, it applies to all of them. what praetor did was take one of the fields and declare it separately and attached the header attribute to that instead of the line that has a bunch of them. this is why you see two SerializeField attributes in his example
there's no "loop". it doesn't break anything. the attribute is only applied to the one field because it is only attached to the one field declaration instead of to all of them.
is there any way to not apply header to any field?
the header attribute is only applied to the field it is explicitly attached to. if you want to separate a field from others to show it is not part of a group then you can use the Space attribute
but header does not create any sort of grouping, it just draws a header above the field it is attached to
oh so it applies to the first field but since the others are below they look like they belong to the same one ?
it only applies to the one it is attached to
yes because there is no spacing between the fields drawn to the inspector it just looks like a group, but the header attribute is only on the one field it is declared on
alright so this is just a visual thing
yes
public class CommonBehaviors {
public void Attack() {
// Lógica del ataque
Console.WriteLine("Atacando al enemigo...");
}
public void Defend() {
// Lógica de la defensa
Console.WriteLine("Defendiéndose...");
}
public void Heal() {
// Lógica de curación
Console.WriteLine("Curándose...");
}
}
public class Character {
public Stats CharacterStats { get; private set; } = new Stats();
private CommonBehaviors commonBehaviors = new CommonBehaviors();
public void Attack() {
commonBehaviors.Attack();
}
public void Defend() {
commonBehaviors.Defend();
}
public void Heal() {
commonBehaviors.Heal();
}
}
public class Enemy {
public Stats EnemyStats { get; private set; } = new Stats();
private CommonBehaviors commonBehaviors = new CommonBehaviors();
public void Attack() {
commonBehaviors.Attack();
}
public void Defend() {
commonBehaviors.Defend();
}
public void Heal() {
commonBehaviors.Heal();
}
}
so something like this would be a good implementation?
Unless im missing something, both classes here are literally the same. You dont need a separate character/enemy class
in what context?
well i already wrote it
Damn i learned after years of coding today that in c# u should do public fields in PascalCase
stats inside the dictionary are not the same
both classes have the same methods, so I recommend using an interface. Even then, a ScriptableObject approach might be beneficial
Hi, I have the issue that my camera always looks 90 degrees to the left of the intended target.
The lookAt camPivot is supposed to deal with the vertical rotation of the camera, which works fine, and the playercam.forward part is supposed to correct the horizontal rotation to be the same as the player, which the camPivot is parented from. However with this code, the Camera always looks exactly 90 degrees left from the intended target. How do i fix this and are there better commands to copy the horizontal rotation of a transform?
Populating a dictionary differently shouldnt mean you make a new class. Just change how you populate it, like possibly use SO (scriptable objects) to give it data
my gamemanager is a singelton but when i restart game my ui elements gets lost.
here my restart function in my gamemanager scrip and to activate the ui to show restart.
public void RestartGame()
{
// Reload the current active scene
Scene currentScene = SceneManager.GetActiveScene();
SceneManager.LoadScene(currentScene.name);
// Optionally, reset game state variables here if needed
gameState = false; // Example: Resetting the game state to its default value
}
// Function to activate the UI element
public void ActivateDeathUI(bool death)
{
if (gameState == false && death == true)
{
if (deathUIElement != null)
{
deathUIElement.SetActive(true); // Activate the UI element
}
else
{
Debug.LogWarning("Death UI Element is not assigned in the GameManager.");
}
}
}```
If you mean it's DontDestroyOnLoad, then it will still just refer to the original instances in the scene you unloaded
yes my ui elements still in scene, but the reference to it gets lost
Are the actual original instances you have referenced still in the scene
yes
Or, did you reload the scene, which destroyed those instances and loaded wholly new and completely different UI elements
this is how it looks like after restarting.
Yes, and the instances in the Sample scene are completely new instances. They are not the same objects you referenced, the original objects were destroyed and replaced when you reloaded the scene
ah
so i need to store them in prefabs?
because i tried to store them in prefabs and it didn't really worked well.
You can have a UI singleton that doesn't use DontDestroyOnLoad and lives in the scene, so when the new scene spawns the new singleton takes over
but this gamemanager is a singleton
And it uses DontDestroyOnLoad
for every element that needs to survive you need to create a seperate script?
Hello, I'm looking for a framework to help me abstract away series of inputs in a game for the behavior of opponents. I have an abstraction to specify control inputs to a character because I want to make sure that all bot behavior replicates what a player can technically do, so I can specify, tick-by-tick, movements, aim directions, etc.
I'd like to abstract things such that, when I say (for example), "press this input and aim at your opponent for 60 ticks", for example, without having to write out each frame of logic each time. How might I go about that?
And maybe for another example, "input move direction away from opponent for N ticks/until X happens", etc.
Obviously I'll have to write functionality to specify what it means to "aim", "at enemy", "away from enemy", etc.
And in terms of writing these instructions out, I'm fine with the code being written in C#, but it would be cool if I could use some more expressive DSL
when one of my elemens survive, new one are put in the game, but then you get a overlap
so what's like, reasonable as far as waiting for a bugfix. like i was naively assuming they'd fix my super clear ez repro case in the next minor version, but it's been two months and 10 versions since i posted the bug
starting to worry Unity will drop 2022 LTS before even getting to it
i dont get it what else do i need to implement to make ui survive
if someone can check my gamemanager
my gamemanager is a singelton but when i
Why check for the canvas separately instead of just putting this script on the canvas you want to persist with this?
Also, what's with the System.Obsolete
that àppeared because of Object.FindFirstObjectByType<Canvas>()
So don't use obsolete methods
not needed anymore basically
and don't use Find anyway
separation of responsibilities, obviously
Just use a singleton that exists in the same scene (doesn't use DontDestroyOnLoad), and don't persist any of it but the game manager.
then you will receive a bug where to ui is destroy, and then game manager cant get the reference to it.
But if this whole object's purpose is to be the UI, then it should actually be the UI
The GameManager references the UI through the UI singleton
and it is
There are a lot of ways to skin a cat
see here what happens
i dont understand why it directly is already in the unload section
Split it up so you have a global DontDestroyOnLoad singleton that persists state,
and a separate UI singleton that doesn't persist that references the UI
can you please use a thread, you're burying this whole channel
Looks like the canvas is disabled
that is the restart canvas, activates when you die.
see here what happens
The timer is what the issue is, right? The timer's not there in the next scene?
yes and then restart canvas doesnt appear again.
The canvas is disabled
You're probably disabling it somewhere and then not re-enabling it again
it works now
bump
Break it down into composite parts:
- an action to do(input)
- when to do it(condition)
- how much times to repeat it
- repeat delay
- exit condition
If you define a data structure with these data you can virtually queue any kind of actions sequence. You can also have utility nodes like Sequence and Parallel to make several of these run in the desired order or at the same time.
Correct me if im wrong, but what you described sounds similar to how a Behaviour Tree works?
It is indeed very similar. Though a third party solution might not offer enough flexibility for their use case, which is why I'd consider writing a custom solution
Interesting, I remember seeing a tutorial for a custom one built with UIToolkit a while ago, BTs seem very flexible once you can get them setup
Break it down into composite parts:
That was probably more of an ui interface for setting up and debugging the behaviour tree.
Thinking of it more as of an algorithm rather than visually connected tree of nodes, could open a lot of different use cases with it.
Yeah, from what I remember it was a implementation to visualize the creation and connection of the behaviours, kind of like the Animator window, though maybe its easier to build outside of the visual tooling
still struggling with this
you need to minimize the problem before anyone can help. Create a dev build and continue printing to console
okay
It's probably something with your camera/raycasting method so figure out where
I'm going to focus on the actual problem and not assume:
he refuses to specifically see me ... ive checked the console ... but that isnt giving me any errors
So it's not throwing an error (reference exception and whatnot - the basics)
InDetectSlasher, log what the raycast hit and it's layer.
InSlasherSightlog:
- if it's blind, chasing, sees player, touching, and if it's in the mesh.
no errors at all
Of course.
Gamepad input, is that something I should worry about in development or just when I'm about to publish?
development , do you really want to exclude people who prefere controllers
new Unity Input system makes it stupid easy anyway
Yes, but I bought InControl and don't really use it
But I guess it isn't about what you want to use, it's about what's easy to implement
yeah , I just prefer the built-in solution because its Free 😄
as long as rebinding is easy, thats mainly why the new system shines as well
Are there any standard naming conventions for Fluent interfaces? https://en.wikipedia.org/wiki/Fluent_interface I just want to make sure that my callers know that a given method will mutate and return itself
In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.
Not really. Fluent API is just sugar, unless the case like Linq that you generate different object per each chain. In those cases you could add an analyzer attribute to make sure return value is used.
If Evans and Fowler "created" it, it is likely some nonsensical, self-explanatory crap, disguised as something they can sell "talks" about. 😉
The way i see it is that it is just a bunch of chained predicates, no more no less
You're asking a non-code question in a code channel. Delete and ask in #💻┃unity-talk
and do not cross post, delete from the other code channel too.
guys is this value maximum float in unity?
it wont increase no further
3.355443E+07
very confusing
for example i tried to multiply it by 2 didnt work
I've got an issue where Gameobjects that I Instantiate stick around after stopping the game in the editor.
Everytime stop and start the game another appears
I've tried forcing them to destroy when the scene unloads but it doesn't get called.
I'm not sure what I'm doing wrong
Reloading scripts will make them disappear
try this
Debug.log(float.MaxValue)
If your planning on using it with large values then be careful its still accurate enough at the values your using
okay i checked and it happens to float but not doubles
I just might reset my time each in-game day or something
i had this problem for quite a while, i just need some sort of Awake method for non monobehavior (to store to a static collection) but it create duplicates anyone knows a good solution?
Please properly share your !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
As for your question, a non-monobehaviour is supposed to use the constructor.
As for the actual issue; your code is coupled very poorly. I suggest you don't have d add itself to a static list like this. I don't see the point of such complexity
yea but it create duplicates if it serializable
Currently your issue is very hard to debug since your code depends on eachother like this, which makes no sense
Why is it serializable?
I guess it's to show it in the inspector
Does the inspector show duplicates?
i think it just a unity problem
Still, why are you doing this?
Why have a static variable that seemingly does the same thing?
Do you need to access the list from another class?
If so, use singletons and not this mess
i just use this code to present my problem
If this is not the actual code then I suggest you just share your actual code
Nothing about this suggests that there would be duplicates
@crimson trellis
You could do something like this to get it working.
But this is going to run everytime you make a new instance.
private static List<d> slist;
private void Start() {
if (slist == null) {
slist = new List<d>();
// Do your run once code here
}
}
This makes absolutely no difference
Even better, it's worse because your list might not exist when you need it
i just want to make custom class that could have callbacks so i need to store them in a static list
@crimson trellis Your assignment of list from slist might very well cause the issue as Unity might fill it in afterwards with the serialized values
So I still suggest you get rid of this weird system you have and not rely on a static list
So this is an XY problem
You want something entirely different
What are callbacks here? Please explain in detail what you try to achieve
I'd rather give you a proper solution than fix the current one
it mainly for language changes so it callback on everything that is related to language
Do you mean when the user changes their locale, so you can update strings and such that rely on it?
yea
Then I suggest you reverse the process. Instead of adding callbacks, use events
I assume you have some sort of manager for this localization?
In short, you should probably have some singleton that manages this localization. When you update the locale, you inform this manager.
it only gonna be harder if i dont use static , also i think this is a unity serialize problem if i use event it likely will add the event multiple times
When that happends, it triggers an event and tells any depending monobehaviours of the update. These can then update their strings
You have definitely chosen the harder approach here
Also, idk what num would be in this list?
I still don't understand what this list is supposed to contain
it just for testing
But even then, what would this list have if your idea is to support callbacks?
You can't implement delegates into a list through an inspector. That's impossible
This is why there's events
this isnt the actual code, the main problem is that unity create duplicates
Well, until you share the actual code that I requested there's not much I can do for you
So please either share that, or go with my suggestion
But I can ensure you your currently static approach will not work and looks horrible
my actual code is kinda 'fixed' but im searching for a better solution
You mean the solution that I already gave?
Your question revolves around informing depending code on a change in your locale settings. This is what you explained.
The correct way would be to use events, and not callbacks. I don't see how this would even work to begin with
my main problem is that unity create duplicates for things that is serializable ,i just want a safe way to init clas
ses and not rely on monobehaviour
I already told you that constructors exist for initialization when it comes to monobehaviours
So if you're not interested in actually fix your current system, then there you go
Not much else I can tell you at this point
@crimson trellis
What is your code duplicating?
Is it duplicating gameobjects?
Is it duplicating prints to the console?
the slist should have only one 'd'
If you read the issue you'd see that it duplicates class instances inside the list
Sorry I must have missed it
It's okay. The issue is clearly the fact that they try to use a static list for some reason. Something I tried explaining to deaf ears unfortunately
So unless they improve the system, this is unlikely to be fixed
@brah can you post the code that adds to the list?
it in the constructor
Have you tried the code I posted earlier?
I think that will likely fix your immediate problem.
are u talking about a UnityEvent or a delegate? it gonna be tedious if i need to set up a scene with language elements with UnityEvent , if u r taliking about delegate it makes no difference the method will duplicates , can u give me more context about the event u r talking about
Considering you're still trying to fix this issue despite being told multiple times that your current approach is horrible:
You get duplicates because when Unity is serializing the class, your constructor gets called a second time which makes a second instance in the static list
So please start listening to advice that is given to you and get rid of this horrible system
I am talking about nothing until you start sharing your actual !code so that it becomes clear what the end goal is
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Because clearly your current code is simply pseudocode that misses all the context we need here
my problem is very clear: find a way to add a class to a static collection when it created
No, your problem revolves around an XY problem: https://xyproblem.info/
Or in other words, you are currently trying to find a fix to your current solution even though the issue is that you need a proper solution to begin with
So I ask again, share your code
well i 'fixed' that by whenever u use the class u check is the bool isAdded on, if false add to collection and set to true
so i dont have to rely on a constructor
Or in other words you added in another hack on top of the hack you already developed
Clearly you are not interested in actually being helped, or you are lazy
I suggest you seriously consider listening to advice that is given to you next time. I am no longer interested in doing so.
emmm im not sure how your idea would solve the problem,it either also make duplicates or is tedious to set up
It doesn't matter because you're not even considering it to begin with
And considering you have not yet shared the actual code I'd assume this is still the case
I'm having a weird issue where GameObjects I instantiate will stick around in the game scene after stopping and starting the in-editor preview
Has anyone come across this before?
I have a MainMenu Scene which loads to a World scene
I have a "SpaceVesselController" object that does the instantiating, it is also set to Don'tDestroyOnLoad
The gameobject is the players initial SpaceVessel
Stopping and starting the game preview creates duplicates of the initial space vessel in the World scene
Reloading code after changes resets the scene
I tried using SceneManager.sceneUnLoaded += DestroyMyselfFunction() but it doesn't seem to be called when stopping the game preview
I've checked the world scene file and none of these exist there.
So they only exist when playing
FusedQyou do you have any Ideas?
I've run out of things to try
too little context, maybe try restart the editor since unity goes weird sometimes
Share SpaceVesselController
public class SpaceVesselController : MonoBehaviour
{
// Singleton
public static SpaceVesselController instance;
[System.Serializable]
public struct NamedSpaceVessel {
public string name;
public GameObject spaceVessel;
}
public NamedSpaceVessel[] NamedSpaceVessels;
private Dictionary<string, GameObject> spaceVessels;
public GameObject SpaceVesselContainer;
public void Awake() {
// Singleton
if (instance == null) {
instance = this;
} else {
Destroy(this.gameObject);
}
DontDestroyOnLoad(this.gameObject);
// Initialize space vessel prefabs dictionary
spaceVessels = new Dictionary<string, GameObject>();
foreach (NamedSpaceVessel namedSpaceVessel in NamedSpaceVessels) {
spaceVessels.Add(namedSpaceVessel.name, namedSpaceVessel.spaceVessel);
}
}
public void CreateSpaceVesselContainer() {
if (SpaceVesselContainer == null) {
SpaceVesselContainer = new GameObject("SpaceVesselContainer");
SceneManager.MoveGameObjectToScene(SpaceVesselContainer, SceneManager.GetActiveScene());
}
}
public GameObject SpawnSpaceVessel(string spaceVesselName, Vector3 position, Quaternion rotation) {
CreateSpaceVesselContainer();
GameObject spaceVessel = Instantiate(spaceVessels[spaceVesselName], // Get the prefab by name
position,
rotation);
// Parent to the space vessel container
spaceVessel.transform.parent = SpaceVesselContainer.transform;
return spaceVessel;
}
}
restarting the editor removes all the existing SpaceVessels, but they still get created on new plays
Please properly share your !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
edited
This is a recent addition, it has no effect
SceneManager.MoveGameObjectToScene(SpaceVesselContainer, SceneManager.GetActiveScene());
I just checked and SpaceVesselContainer starts in the world scene anyway
can u explain your problem again?
I move from the MainMenu scene to the World Scene
When the world scene starts, I instantiate a single game object from a prefab.
There is only one instance of this object here at the moment
I stop and start the game, navigate through the menu into the world scene.
A single instance is created again,
Now there are 2!
I can keep repeating and more gameobjects all get instantiated in the same spot!
Restarting the editor like you suggested resets it back to 1
But the same issue appears again
are u talking about the darter being created?
your SpaceVesselController seems right sorry couldn't help
Thanks for trying
So the issue is that they persist when you stop debugging?
correct
I found something interesting
I put this on my gameobject, and the space vessel gets destroyed as soon as its created when loading the world scene
public void OnSceneLoaded(Scene scene, LoadSceneMode mode) {
Debug.Log("SpaceVessel: OnSceneLoaded");
Destroy(gameObject);
}
On the other hand this has no effect
public void OnSceneUnloaded(Scene scene) {
Debug.Log("SpaceVessel: OnSceneUnloaded");
Destroy(gameObject);
}
its seems to be getting loaded inbetween scenes?
I didn't think this was possible
so i am getting a weird issue
i have a enemy prefab, inside there is a prefab containing the skeleton mesh + a animator
if i disable this skeleton prefab, my prefab gets instantly teleported to 0,0,0 when playing
it seems linked to the ragdoll physics of my skeleton, because if i removed all parts except 1 with a rigidbody it keeps teleporting
if i disable the rigidobdy it doesnt get teleported (makes no sense since the GO shouldbt be actif on a inactive rigibody
nevermind, seems like if a joint connection is null it goes to world center
guys i want your help in creating shader graph on unity is it possible to create a shader graph that cut the mesh and on th cutting surface it show the inner port of the mesh let assume i have to cut th wooden block thn i also want to show cutting surface of wooden block
Yes
can u guide me brothe i am able to cut the mesh but unable to applly fake inside texture
nope. dunno how to
there are lots of tutors on how to slice a mesh with a shader and fill in though
#archived-shaders might be able to put you in the right direction
Why do many people in unity state not apply MVC? What reasons do you have to not use it?
Is a separation into model and view still commonly applied, with different information flow paradigms?
Didn't you already have a lengthy conversation about it last week
can I state that in game art the physical shape (and thus physics and behavior) is often connected to what an artist is trying to communicate to the user, and therefore behavior and presentation are intrinsically tied in assets, and therefore anything that builds on these assets cannot effectively separate model and view?
yes, (and at unity talk I was referred back to here)
I thought about that conversation, and I made some guesses why one would not separate for instance model and view
the reason I needed to think about it is because it goes against everything in every other software engineering project I have taken on
I hope I didn't bother anyone with the question. I'll just see where my approaches fail then (:
Maybe now would be a great time to learn something new. If you want a similar separation of concerns, look into ECS which uses entity-component-system instead of model-view-controller
thanks, that sounds awesome, the reason I am asking is because I do indeed want to adopt typical game design approaches, I hope that is clear. But that does mean I need to understand the reason my old approaches fail
I really enjoy this MVC approach: https://www.jacksondunstan.com/articles/3092
same guy also introduced an alternative: https://www.jacksondunstan.com/articles/3611
interesting
when I was still a student I designed an architecture for an adventure game, that essentially generated the user interface from events
I really like the ecs pattern
yeah, it's great, but I feel that the current Unity implementation is a bit frustrating to work with
Often times, what you see and what makes sense in a game are different. Mega Man can stand almost completely over a pit because his hitbox is a rectangle, but his arms are wider than his feet so they are visually over nothing. This looks ridiculous, but allows for significantly better movement since you basically have built-in "Coyote time", and it allows you to jump on top of a ceiling directly above you, which can create new paths for those adventurous enough to try it.
In almost every 3D game, your character is actually a cylinder or capsule or some other simplified shape, the mesh doesn't actually do any of the physics calculations.
this is also quite helpful
the way I understand the code and diagrams is that model and view changes often happen at the same time
and therefore, you just needlessly complicate things if you disentangle them...
if you think I don't understand correctly or if I do get it, please let me know!
that depends on your use case, project needs, personal preferences, etc
every architecture comes with its pros and cons
having the model and view decoupled makes it easier to create unit tests and swap different implementations
but then you need to deal with the added complexity of having them decoupled in the first place
From I have seen, almost every sensible implementation of a game implements a "View" and a "Model". The "controller" aspect of the MVC is only implemented when needed and is not done systematically.
That being said, there is really a few situation when it is actually needed in video game. Such situation can be when dealing with non ui-view or with multiple view for 1 "system". By example, I implemented a MainMenu that combines UI Element and World Element. Where it is possible to put the whole logic in the "View" (UI Element), I found it was more natural to add an additional layer of abstraction to handle both. Most of what is done would be inline with what a controller is usually doing.
Hello, I have a bit of a problem. I'm trying out unity's job system by having a big NativeArray with structs and have each job modify a part of the array, like each job does 100 elements or so, with them all accessing unique indexes (like two jobs never read/write to the same place). But there's an issue, unity finds this to be an error and asks for dependency, which is unfavorable.
Using nativeslices causes the same error. Any ideas how to split the data without copying the entire array over and over?
I print the indexes to make sure, and no slices share any indexes.
I did some googling, unbelievable it seems like copying the entire array for each job is the only way to solve this. Maybe the forums I checked were wrong as it'd be pretty silly if its the only way
Theoretically, is it possible to bypass the memory checks? Unless there's an actual problem writing to different indexes of the array in parallel, it should be fine, right?
The issue is that Unity's job safety system is unable to verify that each job is in fact accessing separate parts of the array and can be deemed to be safe. If the safety system's detection was more sophisticated, it might be able to handle your case, but it's not.
If these are completely separate jobs working on the same array, I think you have to use unsafe pointers instead of NativeArray to bypass the safety system.
There are unsafe versions of various NativeX collections, like UnsafeList, but there isn't an UnsafeArray, I think you just have to use pointers directly.
Thank you 🙏
Man, reading you guy's opinions and thoughts around the design architecture of code feels like it can be summed up with: Whatever makes sense, whatever fits and whatever isn't overkill
rider ide says i'm not using this function, but actually i'm within my player script: GameManager.Instance.ActivateDeathUI(death);
In video game, that is pretty much it. Otherwise you add an enormous amount of complexity for no gain. The end goal of "Clean Code" and pretty much every pattern is to make the development easier. If it does not, then it is pointless.
In software development, it is an other story.
i said something wrong?
Is the function that uses that function actually being used anywhere?
Or is it in a different assembly?
yes
If that assembly references this one, you can call it just fine, but if this one doesn't have a reference to that one, then the IDE wouldn't know about it from here
im actually call this function from within the player script
the function intself is in the gamemanager script
weird why the ide says i dont use it
There is also https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeDisableParallelForRestrictionAttribute.html if you know what you are doing
I already got it to work with unsafe pointers, unless I am mistaken those should be more performant?