#archived-code-general
1 messages · Page 342 of 1
Hello everyone, I'm trying to find some ways to reduce my code since the logic is quite similar but I can't find a way.
case "gender":
valuesLabels = new string[EventsXmlEnum.GenderLabel.Count];
valuesCodes = new string[EventsXmlEnum.GenderLabel.Count];
i = 0;
foreach (KeyValuePair<EventsXmlEnum.Gender, string> pair in EventsXmlEnum.GenderLabel)
{
valuesLabels[i] = pair.Value;
valuesCodes[i] = pair.Key.ToString().ToLower();
i++;
}
break;
case "activity":
valuesLabels = new string[EventsXmlEnum.ActivityLabel.Count];
valuesCodes = new string[EventsXmlEnum.ActivityLabel.Count];
i = 0;
foreach (KeyValuePair<EventsXmlEnum.Activity, string> pair in EventsXmlEnum.ActivityLabel)
{
valuesLabels[i] = pair.Value;
valuesCodes[i] = pair.Key.ToString().ToLower();
i++;
}
break;```
Clicking on the log message will highlight whatever object produced it, assuming you added this as the context
Log it every frame and check when it gets not assigned
I have a switch with several cases which focus on dictionaries with different enum keys. Is there any way to make a single loop and pass the enum type as a variable ?
Create a method for the same parts of both cases
Yes, that's what I want to do, but I can't figure out how to make the keyvaluepair work in the foreach loop
What's is even EventsXmlEnum?
It's a class which contains the list of my enums
although, Instantiate is static, so it shouldn't really matter if the prefab gun is instantiating a prefab bullet
it's not like the bullet would go somewhere different than if an actual gun instance instantiated the prefab bullet
ActivityLabel is not an enum though.
Yes, it's a dictionary, but its key is an enum
Two different dictionaries with two different enums as key. The value of the dictionaries are both string though
No
and the Keys are both ints so you should be able to coalesce based on that
No, string types
public enum Activity { Casual, Work, Prework, Latework, Meal, Lunch, Home, Sleep };```
Hm, does it mean I could use a for loop instead ?
You can't cast from KeyValuePair<SomeEnumType, string> into KeyValuePair<Enum, string>, but you can iterate over the dictionary's keys like so:
foreach (Enum key in dict.Keys) {
}
Yes, but how does that help with creating a method to makes both dictionary work at the same time ?
Because even if I create a method, I'd need to pass the dict as a variable ? Which mean I'd need to cast it to its related enum
Though I'm thinking I'm actually using the enums as strings in the end. I could reduce the size of my code by transforming my enum to a list<string> and pass that to the method instead since I don't actually care about the enum type in the end.
It's a bit difficult to wrangle the generic types here.
void Example(Dictionary<Type, string> values)
You could write an IEnumerable<Tuple<string, string>> method that takes a Dictionary<K, string> and that yields the key names and values as tuples
So both are Dictionaries with different keys, if I get it correctly
But that wouldn't work, cause I'd need two methods this way, one for the Gender enum and one for the Activity enym
Exactly
Yeah, so it does work
IEnumerable<ValueTuple<string, string>> GetPairs<K>(Dictionary<K, string> dict) {
foreach (var pair in dict) {
yield return ValueTuple.Create(pair.Key.ToString(), pair.Value);
}
}
i think those are the right method names, at least
private void Example(Dictionary<Type, string> values)
{
valuesLabels = valuesCodes = new string[values.Count];
for (int i = 0; i < values.Count; i++)
{
var value = values.ElementAt(i);
valuesLabels[i] = value.Value;
valuesCodes[i] = value.Key.ToString().ToLower();
}
}
(i used ValueTuple because it nominally reduces the amount of garbage you create; that's not terribly important)
You could also directly write into the arrays if they're fields of your class, yeah
How does creating 2 methods makes the code simpler ? It would contain the exact same code as in the switch, wouldn't it ? I wanted to find a way to have a single method handle both enum, because I'll have 10 more enums this way
Yeah, haven't I just shown you a single method?
I can't use Dictionary<Type, string>
This should work for both cases
the dictionary's keys are a specific enum type, not a System.Type
Type is not valid
you need a generic method
Ok, thanks for the code, I don't know what ValueTuple does, I'll check online.
it's a value type that's basically just
public struct ValueTuple<T1, T2> {
public T1 Item1;
public T2 Item2;
}
defined for varying numbers of items
Hm interesting. That seems to solve my problem indeed. I'll give it a shot. Thanks!
But the return in VS says (string, string). How do I use the method ?
it's a pair of strings
I've never since this type of return
because it's a tuple
var (foo, bar) = ("one", "two");
i hope that's actually the right syntax
oops, single quotes
i've been writing python recently
#archived-code-general message did you do this?
it only took a few tries 😉
private void Example<T>(Dictionary<T, string> values)
{
valuesLabels = valuesCodes = new string[values.Count];
for (int i = 0; i < values.Count; i++)
{
var value = values.ElementAt(i);
valuesLabels[i] = value.Value;
valuesCodes[i] = value.Key.ToString().ToLower();
}
}
foreach (var (key, val) in GetPairs(dict)) {
// ...
}
there we go
perhaps the gun config has a bullet life of 0
Damn I'm amazed, that works lol.
you should find out what's actually happening
Thanks a lot @heady iris !
okay, so do some logging to find out if the bullets are getting instantiated at all (check if Start runs)
find out when they destroy themselves
T seems to work, interesting. I'll give it a shot too. Several ways to do the same things is good learning I think 😄 Thanks !
What does this mean? Do you see them in the hierarchy?
That just proves that the message was logged
Where’s the proof that you actually created a new instance?
e.g. logging the new instance
You should log something in all those if statments. What if those statements are not passing
(i.e. it doesn't have those components)
You've got a lot of GetComponents in here
Get rid of them. Put public fields on your bullet class that reference those components
then reference the bullet prefab as a Bullet instead of as a GameObject
I'd probably just make the Bullet script handle all this, and pass it the gunConfig reference to do all its business
yes
exactly
Bullet bulletScript = bullet.GetComponent<Bullet>();
if (bulletScript != null)
{
bulletScript.SetDamage(gunConfig.bulletDamage);
bulletScript.SetLife(gunConfig.bulletLife);
bulletScript.SetExplosive(gunConfig.explosiveAmmo);
bulletScript.SetPenetration(gunConfig.bulletPenetration);
bulletScript.SetImpactParticle(gunConfig.bulletImpactParticlePrefab);
}```
This is crazy
why not just:
bulletScript.Setup(gunConfig);```
the rest happens inside Bullet
instead of a wall of GetComponent and setter-method calls
Now make it set its velocity in Start, as well as turn its sprite renderer on
The gun should not have to dig around in the game object to find random components.
It should just tell the bullet that it's been fired
That's why I suggested doing this.
Your prefab has a Bullet on it. Bullet has public fields on it that hold references to the components you need.
Later, you can make the fields private and move the behavior into a method (just like you've done here with Setup)
But for now it can literally just be a public SpriteRenderer bulletRenderer; field on Bullet
Zero GetComponent calls are needed.
Assign the reference in the bullet prefab.
public class Bullet {
public Rigidbody rb;
}
...
public class Gun {
[SerializeField] Bullet bullet;
public void Shoot() {
var shot = Instantiate(bullet);
shot.rb.velocity = Vector3.forward;
}
}
That's it.
In the bullet prefab, drag its Rigidbody compoennt into the rb field
I have a problem similar to my question above which was about dynamic enums
^^ this is a sure way you know everything is plugged in
This time it's dynamic classes
case "map":
valuesLabels = new string[Maps.instance.list.Count];
valuesCodes = new string[Maps.instance.list.Count];
i = 0;
foreach (KeyValuePair<string, Map> pair in Maps.instance.list)
{
valuesLabels[i] = pair.Value.label;
valuesCodes[i] = pair.Key;
i++;
}
break;
case "job":
valuesLabels = new string[Jobs.instance.list.Count];
valuesCodes = new string[Jobs.instance.list.Count];
i = 0;
foreach (KeyValuePair<string, Job> pair in Jobs.instance.list)
{
valuesLabels[i] = pair.Value.label;
valuesCodes[i] = pair.Key;
i++;
}
break;```
all my classes have a "Label" field. Is there anyway to centralize my code into one method like before ?
You could create an interface.
ILabeled, perhaps
It would declare a property called Label
note that this is not a field
public interface ILabeled {
public string Label { get; }
}
each class that implements the interface must have a Label property
using UnityEngine.Localization;
namespace Pursuit.Interfaces
{
public interface IDescribable
{
public LocalizedString Label { get; }
public LocalizedString Description { get; }
}
}
i have something similar going on
Once they have the interface, how would that work in the method ?
Oh, what's the LocalizedString type ?
public void DescribeIt(ILabeled labeled) {
Debug.Log(labeled);
}
Ok thanks
That's part of the Localization package. It's basically a key for a localization table
it can be turned into a string in various languages
Damn, I didn't know about that lol. I'm using a custom translation class and some external json files
I'll have to look into it. Thanks for the tip !
The former is worse in every way.
It's brittle (you depend on exact GameObject names and on the exact hierarchy layout)
It's also slower (you have to search for the child by name)
Optimization is more-or-less irrelevant here, though
You should be much more concerned about correctness
sounds more like the bullet isn't visible
You could put a Debug.Break() after you instantiate it then look for it on the hierarchy , select it and press F in the scene view.
it will pause the simulation
so you can see whats happening to bullet
yes, you would have to debug it
bingo
there are usually lots of system trying to work in harmony together , you gotta be like the maestro know whos doing what at all times
yeah
then you can even press the advance by frame button
its an engine! take advantage that its a simulation and not "real life"
sometimes for debugging I slow my timescale to nearly 0
{
valuesLabels = valuesCodes = new string[values.Count];
for (int i = 0; i < values.Count; i++)
{
var value = values.ElementAt(i);
valuesLabels[i] = value.Value.Label;
valuesCodes[i] = value.Key;
}
}```
I'm trying this way but it says .Label does not exists on the IEntity when the interface does have the public string.
This is a generic method whose generic type is named IEntity
This has nothing to do with the IEntity interface
Get rid of the generics.
Oh yeah, the copy/paste from the enum version had the type which is not needed here
Thanks!
Pause the game. Select the bullet in the hierarchy. Look at it.
You don't need to squint at pixels or log huge amounts of stuff here
Select the bullet and look at where it is and which components it has.
If there is no bullet in the hierarchy, then it's immediately destroying itself after its creation.
Is using the subscriber pattern for player controls a good idea, or is there some sort of built in thing that would be better than whatever junk I write
Hm, still not working.
If you use the new Input System, many of the ways to use it are event based
InitValuesFromEntity(Scenarios.instance.list, ref valuesLabels, ref valuesCodes);
The list is a dictionary of <string, Scenario> and the Scenario class implements the IEntity
either by subscribing to an event or by having it send messages
Oh right, I forgot an important thing.
Dictionary<Foo, Bar> is not compatible with Dictionary<Foo, IEntity>.
Right, duh.
So you will be using generics!
Oh lol
Ohhh I see! I'll do it this one time as practice though :)
public void DoSomething<T>(T arg) where T : IEntity { }

Too bad, that would have solved that
You can constrain the generic type parameter.
It can now be anything that derives from IEntity
As a rule of thumb, I use events for "button" actions (jump, shoot, punch)
No.
But it does explain why the bullet is invisible
what about movement inputs?
Sprite renderers don't have anything to do with collision
and I just directly read values for continuous things, yeah
But is it possible to pass a dictionary of class derived of IEntity ? Because I'd need to pass various dictionaries directly
Makes sense since they are a one time happening thing every time
Thanks!
you'll do this with a Dictionary<string, T>
Ohhh ok. Sorry, first time trying to code this way
I see. I'll try
I'm afraid I'm still stuck :X
InitValuesFromEntity(Scenarios.instance.list, ref valuesLabels, ref valuesCodes);
void InitValuesFromEntity<T>(T values, ref string[] valuesLabels, ref string[] valuesCodes) where T : Dictionary<string, IEntity>
The error says it cannot convert Scenario to IEntity ? But Scenario does implement IEntity
Did I mess it up somewhere in the code ?
Ok nevermind, I did mess up, the T is supposed to replace the IEntity only, not the whole dictionary
void InitValuesFromEntity<T>(Dictionary<string, T> values, ref string[] valuesLabels, ref string[] valuesCodes) where T : IEntity
This works now. Thanks a lot @Fen. You're on fire tonight 😉
you don't need to pass the arguments as ref
unless you are assigning to the arrays, I guess
in that case go nuts
you need to pay way more attention to what you're doing, then
you've got references pointing all over the place
hi so I've tried to create a duplicate inventory system to one i already have and I'm trying to figure out what the issue is here, it's meant to pick up the picture and add it to the wallet inventory but it doesn't pick it up or add it properly. Is it something with me changing names? I only changed names so that it wouldn't interfere with the other inventory system, I can show the scripts for it if needed.
what do you mean by "changing names"? Why do you have multiple inventory systems?
You seem to have a NullReferenceException here
I would start with that
i wanted to create a basic inventory system for basic items and then one for stuff I wanted to show up in a wallet thing
how would I fix this
It's a NullReferenceException - like any other
identify what is null and why
and fix it.
go to the filename and line number indicated
this is very vague and doesn't mean a lot to outsiders who don't know anything about your game
What are "basic items" and "wallet things"
like i just wanted items to go into different inventory systems for asthetic reasons
It's not clear what you mean by "inventory system"
you don't need to copy-paste your code if it's just putting the items in two different places
This kind of code is probably why it's not working
To me "inventory system" means a bunch of code that makes inventories work
You certainly don't need more than one set of such code
digging around the hierarchy by name and using GetComponent all over the place
You should have a StoredItem component that has fields for things like the text and image components
reference the prefab as a StoredItem, not a GameObject
I did this for the other one and it works so I'm confused
how would I have one script put items into two different locations?
why aren't you instantiating this as a separate object that already holds those references..
you never should have to GameObject instance = Instantiate etc.. thats pretty useless tbh
I was following a tutorial thing ngl
tutorial is bad
You didn't understand the tutorial well then
ItemUIThing uiInstance = Instantiate etc..
uiInstance.Setup(stuff etc
tutorials are for getting ideas and understanding techniques. They're not for creating a finished system that you apply directly to your game
you use the techniques to build your own system that works in your game
If there an way to spawn a VFX graph at a list of positions (with only one component) ?
I remember reading about sampling positions from a texture
I don't get what you mean here am I not meant to use the tutorial? I'm just trying to figure out why it works for one and not the other and how to fix this and I'm still very confused
You can use Events (VFX graph terminology) to spawn "batches" of particles.
https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@12.0/manual/Events.html
https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@12.0/manual/EventBinders.html
The event can contain a position if you wish
tutorial is for learning
once you learned, you build your own similar system but in your game
the reason it's not working is obvious - you're getting a NullReferenceException
Your code is looking for very specifically named objects in very specific places
which don't exist here presumably
If you don't understand any of this it doesn't seem like you understand your code at all
Which means it's probably time to stop trying to implement inventory systems and time to go learn scripting / C# basics.
i get the basics of it if not fully I'm new to this
I know you're new
and that's why I'm recommending you start with the basics
You may think you understand the basics but if you don't understand a NullReferenceException or how to fix it, then you do not understand the basics
that is why I'm asking but okay
And I have given you advice already on where to start
go to the filename and line number indicated in your error and figure out which reference is null and why
Is there a way to make a UI Image block mouse input so that the OnMouseEnter function is not called on game objects covered by the UI Image?
don't use OnMouseEnter for the GameObjects
Use IPointerEnterHandler
and you will get this behavior for free
it indicated line 36 so I'm not sure
I'll try this and see if it fixes the problem
that means you need to run it again and get a new line number
and make sure oyu're looking in the correct file
Note you will need a PhysicsRaycaster on your camera for it to work
Thanks. This worked.
It always does!
When my ScriptableObject is renamed, I rename an Asset associated with it, whose variables seem to be reset. The methods I have tried to save the changes with are listed in the order I've tried calling them:
EditorUtility.SetDirty
AssetDatabase.SaveAssets
AssetDatabase.Refresh
However, this does not seem to work. Nothing happens with the Asset when not renaming it via AssetDatabase.RenameAsset
What's the best way to do a double ended queue?
I have a history of locations, I only want to store the most recent ones (Adding as location gets updated, removing from the back as you get too far away), but I don't know exactly how many recent ones I want to store at any given time
That sounds like FIFO so a Queue
oh my god you're right I'm so dumb
I have this scene which works fine in the editor but when building I get this parsing error , I went to look at the file in code and it looks just fine at those lines
This is the screen. I want to make a grapplinghook for the player to shoot a raycast on the wall. The problem is that I am trying to make this on mobile so the player has to click on the screen to show where the grapple would go to. And Im not sure how it would go because the grapple is in the player. This is in Unity3D and I have been battling this for couple of days how to implement it. Any tips?
This is the code where I start the grapple. I havent gotten into grapple execution part because the start of the grapple is already so challenging for me.
the same way you raycast it
get the result of the Hit that point by doing a ScreenToRay
@rigid island I feel dumb
whats the problem ?
Ohh Okay lol
you still need way to store that pos, just for showing purposes like if you're trying to make a marker
But the original Position of the Raycast comes from the gun that the player is holding. So is it: Take the Raycast end point from the ScreenToRay, save it and create a new vector that is the Guns position and the end point?
Ok I think I got something from this conversation. Thank you @rigid island
How can I configure this in my Unity project. I don't want to set "Dev Build"
^this is using Android Studio
Turn on Project Settings > Player > Android > Publishing Settings > Build > Custom Main Manifest, and you can just add that in there.
what's considered good practice when it comes to data that needs to be saved?
for example a Player Monobehaviour has a Inventory variable that needs to be saved, should Player have a function to serialize and deserialize the Inventory or should Inventory be serialized and initialised with a function that takes in the saved Inventory? or another way?
turns out when you hide your events manager that handles panel changing while changing panels you can't change panels anymore 
There aren't really "good practices" in regards to specific features.
The way I'd implement it is by having a set inventory method on the character that assign the inventory data to it's inventory. This function would be called from some kind of manager, like GameManager or PlayerManager, that would take care of loading the inventory with the rest of the player data.
Similarly, the save process would be handled by the game manager, perhaps involving some events.
I can already see some issues with it, though, so it's probably gonna take several iterations of trial and error to make a good system.
okay gotcha ty, that's basically what i do now with Monos having a specific Data object tied to them that's assigned with a function
one issue i've found is if the gameobject is deleted the data still exists in the code not tied to any object, so it keeps running and has a high chance of causing an exception
private AIBrain _brain;
public AIBrain Brain { get => _brain; }
private void Awake(){
_brain = new AIBrain(this);
}
private void Update(){
if (_brain == null){
Debug.LogWarning("Brain is <color=red>null</color=red> at Update");
}}
private void FixedUpdate(){
if (_brain == null){
Debug.LogWarning("Brain is <color=red>null</color> at FixedUpdate");
}}
Why would a variable be null on FixedUpdate but not on Update?
I am perplexed
Debugging it just gave me more questions
For example if it's assigned at the start of fixed update(or end of update) and unassigned at the end of fixed update(or start of update).
that can't be it, there's only one line of code that assigns that variable and its on awake
It could also be that it's getting destroyed. c# objects are not destroyed together with the underlying C++ object, but unity overrides the null check such that it returns null in that case.
Another possibility is that you have several of these scripts both with assigned and not assigned value
but if its destroyed than how would it exist on update..
The C# object exists as long as you reference it, since the GC can't collect it.
But yeah, it might imply that there's a difference between fixed update and regular in how the null check works, so I don't think that's it
oh wait i think i got it, i think i'm overwriting it in an inherited class
Thanks
technically that was the correct answer, but it was an inherited class not multiple of the same script
what's Unity 6??
its Unity, but 6
:|
ya it used to 5, then it went all wacky with years n stuff then they decided that aint cool nomo . So now its 6
no I mean- what's difference from other editor version?
How do you debug shaders not working? I've been having shader issues with the built version of my game using glTFast, where they work fine in the editor, but don't in the built version. I tried adding a shader variant collection and added it to preloaded shaders, and while that fixed most of the textures, some still show up wierdly, like the chair in the image still showing up as silver. I'm pretty confident its a shader issue since I've fixed most of the textures with the variant collection, but I'm not sure if I missed any
I tried enabling developer mode to access the debug console in the built version but glTFast doesn't give me any errors or anything like that regarding missing textures/shaders
You'd use a dedicated shader debugging tool, like the one included in Pix for windows and Xbox. Other platforms have their own tools.
One reason why it's different in the build is that a different graphics API is used in it. You can check the graphics API settings in the project settings - player. Try different ones to see if it fixes the issue.
Where are the graphics API settings? I checked under Player - other settings and don't see anything relating to a graphics API
Am I understanding this correctly? First time setting up a state machine and I think I mostly understand how the logic works. The way this constructor argument is setup vs something like MonoBehaviour is that I'm strictly defining the variables in each state I'm passing as a reference to the player's main script? This is the call that would explicitly make it happen (minus the rest of the setup)?
I realized it's a very vague question to say something like "am I understanding how constructors work instead of just copying what I see on a YT screen" lol.
Check under other settings - rendering in player
Take a screenshot
It's setting values for each "new state" (or in this case as I enter a state).
I'd assume this is it
but nothing about using a different graphics thing than the editor
Are you sure you are calling the constructor each time you enter a state? This seems like a rather poor implementation
No. Take a screenshot of the whole thing.
Do you see the auto graphics API for windows/Linux/mac? Uncheck that and a list would appear.
ah at the top. Got it
Yeah admittedly it's a bit ghetto but I'm rocking with it temporarily. Generating a "new state" every time I enter it is a little oof but for a starter project it's good enough so long as I understand how it's working.
The more time passes the more I learn there are a lot of bad tutorials out there.
which API should I be looking to use?
Maybe start with trying opengl.
Though, I'd imagine that editor uses d3d11 or 12 on windows.
Thats so bad I would not even consider it decent for a starter project. Why not learn correct things from the start ?
This might be a done to death question, but my struct isn't appearing in the inspector. A google search didn't really help
Struct Definition:
[System.Serializable]
public struct DataTag : INetworkSerializable
{
FixedString32Bytes key;
float value;
Implementation:
public class ItemDescription : ScriptableObject
{
public GameObject prefab;
public Sprite icon;
public ItemType itemType;
public uint weight;
public DataTag dataTag;
}```
both are private
also not even sure FixedString32Bytes is serializable ?
uhm.. how do I solve this error?
SceneView rotation is fixed to identity when in 2D mode. This will be an error in future versions of Unity. UnityEditor.GenericMenu:CatchMenu (object,string[],int)
Doesn't look like an error
Looks like a warning at worst
I am trying to make a conveyor belt that moves every rigid body on it a certain direction. Howerver, this doesn't seem to be working:
using UnityEngine;
public class ConveyorBelt : MonoBehaviour
{
public float speed = 5f; // Speed at which the conveyor belt moves objects
void OnTriggerStay(Collider other)
{
// Check if the object has a Rigidbody component
Rigidbody rb = other.GetComponent<Rigidbody>();
if (rb != null)
{
Debug.Log("ConveyorBelt: Rididbody detected");
// Move the object along the conveyor belt
rb.velocity = new Vector3(speed, rb.velocity.y, rb.velocity.z);
}
}
void OnTriggerExit(Collider other)
{
// Reset the object's velocity when it leaves the conveyor belt
Rigidbody rb = other.GetComponent<Rigidbody>();
if (rb != null)
{
rb.velocity = Vector3.zero;
}
}
}
Maybe other doesn't have a collider or rigidbody
What doesn't seem to be working?
Translated from code into English, this says:
When another object whose collider is set to IsTrigger continues to collide with me and has a rigidbody, set that rigidbody's velocity to (x = speed, y = its own pre-existing y-velocity, z = its own pre-existing z velocity). Whenever it stops colliding with me, set its velocity, if it has a rigidbody, to zero.
It could be failing for a few reasons:
- You did not intend to only set the other rigidbody's x-axis movement vector to a velocity of
5f - OnTriggerStay and OnTriggerExit trigger rapidly while an object bounces around on top of the conveyer belt
- The colliding object collided with a child object, so
GetComponent<Rigidbody>()is returning false and exiting early - The speed is too little to be visually recognized
- The script is not attached to the correct object
Add more debug logs and find the exact point of failure if you can.
Hi ! How can i get this value as a variable from the mixer ? i know how to get the fader value but this one i can't find a way to do it
Hello, im making a custom level editor in my game and i have some questions. Currently i can edit position, rotation and scale values of objects when i click on them but i want to add custom parameters for specific types of objects .For example when i click on a vehicle it should show a speed value that can be editable, an explosive object should display explosion force and damage. Whats the best way of doing this without making spaghetti code?
This for runtime or in Editor?
runtime
For dynamic input dialogs I would use a 100% code based UIToolkit system
what do you mean
i have this script that is attached to multiple characters and there is a randomizer for that script
but that script will only output same randomized numbers for all the characters, how do i make it different output for each one?
what don't you understand about what I said?
isnt uitoolkit system used to create ui for games
why would i use it to create custom objects in my level editor
how do you expect to collect input?
inputfield
which is UI is it not?
yes
so why not UIToolkit?
whats the difference
UIToolkit is very much more flexible to create dynamic UI dialogs in code
How to get different output, properly get random numbers. You need to show what you tried
the code is working fine, its just that im using the same script for all the characters
and this script is generating the random numbers same result for all the characters
so for example
player 1 has generated random numbers of 2 3 1 4
all other players has also 2 3 1 4
im using visual scripting if you can read that i can show
you probably want to use System.Random, where you can have a unique Random class instance for each character
Then you probably need to ask in the server for that #763499475641172029
I assume your visual scripting stuff is creating a random instance with the same seed for each character which is why you get this issue
yes
how do i make different seed for each character?
does this generate different seed?
if you ask it to, yes
how? what is the method to call?
you could use something like the instanceId of the character as the seed
what's a good way of structuring data?
for example: i have a Object1 class that has ObjectData1, but this Object1 can contain Object2 which needs ObjectData2 and maybe even a third Object
my approach is just having an initialise method in Object1 that takes in ObjectData2, but i feel like there has to be a better way to do it
Abstract classes and/or Interfaces and Inheritance
i do make use of inheritance but i still need Object1 to have Object2 and its data
example:
Cells in a grid, each Cell can contain Land, and each Land can contain a Structure
then why doesn't Object1 inherit from Object2 ?
because i might want one to be able to exist without the other, a structure that doesn't need to be placed on Land in this example
then you need Interfaces
using this example, in what way would that be structured?
So your grid would be of type ICell
ICell would inherit from ILand
ILand would declare a Structure property
So any class which inherits from ICell must implement the ILand properties but can leave them null
you could do the same with abstract classes as well
hm ok i'll look into this more ty
Hello, I need your help please. I work on a dialogue system based on this tutorial : https://www.youtube.com/watch?v=3LfpzaFqNsc. My text is invisible on screen but all my settings are good, I check my code, I don't see any error. I don't have error on my console. I never had sometimes like that and I don't see any report on internet for that. Can you help me please ?
NOTE: If you cannot see your character's text (dialogue or name) after applying a color to it, make sure that the alpha/transparancy of the color is set to 1! That's a sneaky thing I forgot to mention.
Let's take the customizations defined in our configuration file and apply them to the character's text appearance on screen
Video Resources:
Fo...
Well, you can see that blue text?
the blue text is when I update the color but If I used the default settings I create it doesn't work
ok what im more curious about is how to setup the code logic
Could you show the screenshot of the text with default color?
I create a scriptable object to set my settings. Then my Dialogue Manager get the chracter name " DL_Character character = DL_CharacterManager.instance.GetCharacter(speakerName);" based on the string name
then we get the config " DL_CharacterData config = character != null ? character.config : DL_CharacterManager.instance.GetCharacterConfig(speakerName);" and apply it on screen
I know that is this portion of code that doesn't work :
public void ApplySpeakerDataToScreen(string speakerName){
//Get the name of the Character
DL_Character character = DL_CharacterManager.instance.GetCharacter(speakerName);
//Get the configs of this character (exist or default if don't exist)
DL_CharacterData config = character != null ? character.config : DL_CharacterManager.instance.GetCharacterConfig(speakerName);
//Apply the Color and Font
ApplySpeakerDataToScreen(config);
}
I have some sprite grids in the scene and zoom in and out functions using a camera, the issue is when I zoom out the sprites start to flicker and some parts disappear like half displayed(see video). please help to solve this.
This is the question to Unity's rendering. You may ask in #💻┃unity-talk or some other rendering channel, not sure whether there are settings to change fix this.
I don't understand ^^'
What is your issue?
And I've mentioned sending code
this way
My text is invisble on the screen but has color asign
I'm begginer in c# code so I don't understand all thos thing
Oh, you're the one with this issue
Sorry, haven't mentioned
ah aha ok no problem ^^
So have you read this message?
yes thats it
I'm talking about your text in the scene
I try to understand why my text is invisible because is apply
Alright, now show the position of your text in the scene
The position on axis ?
The position is good, is not a problem of hiding the message
The color opacity is zero
The message is displaying, it^s not a problem of color, z-index, set active or other. If I desactive this void :
public void ApplySpeakerDataToScreen(string speakerName){
//Get the name of the Character
DL_Character character = DL_CharacterManager.instance.GetCharacter(speakerName);
//Get the configs of this character (exist or default if don't exist)
DL_CharacterData config = character != null ? character.config : DL_CharacterManager.instance.GetCharacterConfig(speakerName);
//Apply the Color and Font
ApplySpeakerDataToScreen(config);
}
it show on screen but only in black
Oh fuck ! you are right ahahah
How ??
Mentioned by Nitku above. The color's alpha is set to 0. You'll have to increase it for the message to be visible
I was thinking about the possibility of opacity being 0, but, for some reason, I thought black is 1 and white is 0.
me too, I probably have a bug when I modify the color and I didn't realize it was pasing in 0 opacity because it was good at first
The color in code is coding like Color(red, green, blue, alpha) right ?
nameColor = new Color(nameColor.r, nameColor.g, nameColor.b, nameColor.a);
That's the correct order, yes
note that these are in the [0..1] range (for non-HDR colors)
Yes, Color can be also created without the 4th parameter, a, which makes it 1
Ok so by default .a = opacity to 1 I don't need to specify that
Thank you, I'm learning
I have a class A like so:
public class A{
public List<Data> inputs = new List<Data>();
public List<List<Data>> outputs = new List<List<Data>>();
}
I have a subclass of it like so:
public class B : A{
public List<Data> outputData = new List<Data>();
public B(){
//Setting inputs
//Setting outputData
outputs.Add(outputData);
}
}
Now, for some reason, when I save instances of B to a json file, inputs does appear while outputs not. What could be the problem?
Yes, you can see it when opening the Color struct and when typing Color color = new( and pressing
Ctrl + Shift + Space
@latent latch "If you need data that can be assigned in the inspector"
Yeah, that was the general usecase, but I was running into situations where I needed both regular classes and SOs that can be assigned in inspector, such as having situations where character stats could be assigned via an SO template, but also generated during runtime using custom classes.
So I eventually ran into hiccups, where I was using SOs directly, for templates, but that locked me out of clean methods of using other class types, when I needed to go back and refactor my code for it.
are you using JsonUtility? it can't serialize lists of lists, you would need a wrapper class for the items in outputs
So a class with a list of Data? And have a list of those?
yeah exactly, it can serialize any serializable class, and lists of any serializable class, but lists themselves aren't serializable classes
nice (:
You mostly need GetComponent in places like physics messages (OnTriggerEnter, etc)
In those cases, TryGetComponent is really helpful
if (!collider.TryGetComponent(out Foo foo))
return;
foo.Bar();
Ok, thanks!
I maybe found some strange behaviour? I have 2 instances of the same class behing inherited by another class. The OnEnable on one of them does run, on the other it does not. The only real difference is that one sits as a child of a DontDestroyOnLoad object. Is this an intentional Unity feature or am I just messing up elsewhere?
It returns a bool that tells you if it succeeded. The component gets written into the out argument
if (!hits[i].TryGetComponent<Entity>(out var target))
continue;
if (target == entity)
continue;
if (!target.TryGetModule<Grabbable>(out var grabbable))
continue;
Grab(grabbable);
This is used to pick up an object. It does several checks in a row, including a TryGetComponent
(TryGetModule is really similar)
my entities have modules attached to them. they aren't necessarily on the same object, so I made a little system to keep track of all of them
I would still track that without using GetComponent
When you equip a weapon, store a reference to it in a field.
What's the rigidbody needed for?
The weapon component should contain a sprite.
do you mean two different subclasses of the same base class?
Yes
I can quickly show code if neccessary
(its not much, like 10 lines)
Menu.cs
protected virtual void OnEnable()
{
SubMenu.ElementChosenEvent += OnElementSelected;
Debug.Log(gameObject.name);
}
public virtual void OnElementSelected(int menuId, int subMenuId, int id)
{
Debug.LogWarning("Unimplemented OnElementSelected called.");
}
SettingsMenu.cs
public override void OnElementSelected(int menuId, int subMenuId, int id)
{
Debug.Log("Settings menu: " + menuId + " " + subMenuId + " " + id);
}
SubMenu.cs
Debug.Log("Submenu:" + menuId + " " + subMenuId + " " + Locked);
ElementChosenEvent?.Invoke(MenuId, Id, id);
The SubMenu print is called, the print in SettingsMenu is not. The OnEnable in the Menu is not called for the SettingsMenu object. I have other Menu derived classes, and the OnEnable is called for them. SettingsMenu does not override the OnEnable
It worked. Thanks again!
OnEnable is virtual, is it being overridden?
not in SettingsMenu
oh, never mind
Right. You just display the sprite the weapon gives you
is there any chance SettingsMenu accidentally has its own OnEnable, not overriding the virtual method? (there's normally a warning for this)
no
If you need more than just a sprite, then I would give each weapon a prefab
Ok some new info, if I tick the box on and off in the inspector it gets called, it just doesnt get called the first time
hmm but it's definitely active and enabled to start with?
yes
Okay -- so what I would do is make the WeaponPickup component contain a reference to a prefab
When you pick it up, you instantiate that prefab and put it in a list of weapons you currently have
Uno momento, it seems to randomly disable itself in a frame
I guess that's the problem
just gotta figure out why the frick it happens
thank you for help tho
Where does the actual shooting logic go?
I'm trying to simulate a swerve drive robot in unity by using 4 WheelColliders and a RidgidBody. The entire chassis is super jittery and it moves in weird ways because of that. The other issue is it's insanely slow no matter how high of a number I set the rotation speed and motor torque. This is my code for controlling each module
public class SwerveModule : MonoBehaviour
{
[SerializeField]
private WheelCollider wheelCollider;
[SerializeField]
private Transform wheelTransform;
[SerializeField]
public float wheelAngleOffset = 0f;
private float desiredAngle;
private float desiredSpeed;
public void setModuleState(float wheelSpeed, float wheelAngle)
{
desiredAngle = wheelAngle;
desiredSpeed = wheelSpeed;
}
void Start()
{
desiredAngle = 0f;
desiredSpeed = 0f;
}
void Update()
{
wheelTransform.localRotation = Quaternion.Euler(0, desiredAngle + wheelAngleOffset, 0);
wheelCollider.steerAngle = desiredAngle;
wheelCollider.rotationSpeed = desiredSpeed;
wheelCollider.motorTorque = desiredSpeed * 10;
}
}
this is how im determining what numbers to provide to the swerve module
private void CalculateAndSetModuleStates(float vx, float vy, float rotation)
{
float A = vx - rotation * (robotLength / R);
float B = vx + rotation * (robotLength / R);
float C = vy - rotation * (robotWidth / R);
float D = vy + rotation * (robotWidth / R);
float[] wheelSpeeds = new float[4];
float[] wheelAngles = new float[4];
wheelSpeeds[0] = Mathf.Sqrt(B * B + D * D);
wheelSpeeds[1] = Mathf.Sqrt(B * B + C * C);
wheelSpeeds[2] = Mathf.Sqrt(A * A + D * D);
wheelSpeeds[3] = Mathf.Sqrt(A * A + C * C);
wheelAngles[0] = Mathf.Atan2(B, D) * Mathf.Rad2Deg;
wheelAngles[1] = Mathf.Atan2(B, C) * Mathf.Rad2Deg;
wheelAngles[2] = Mathf.Atan2(A, D) * Mathf.Rad2Deg;
wheelAngles[3] = Mathf.Atan2(A, C) * Mathf.Rad2Deg;
float maxWheelSpeed = Mathf.Max(wheelSpeeds);
if (maxWheelSpeed > maximumSpeedMetersPerSecond && maxWheelSpeed > 0)
{
for (int i = 0; i < wheelSpeeds.Length; i++)
{
wheelSpeeds[i] = wheelSpeeds[i] / maxWheelSpeed * maximumSpeedMetersPerSecond;
}
}
for (int i = 0; i < swerveModules.Length; i++)
{
swerveModules[i].setModuleState(wheelSpeeds[i], wheelAngles[i]);
}
}
Is a WheelCollider the wrong approach to this? And is the jittering from the suspension in the wheel collider being too stiff?
Hi yall, are the c# youtube tutorial any good?
Yes and no.
!learn is better
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
can someone explain how to get children reference in unity toolkit hierarchy with script?
how do you know what gun the bullet came from?
📃 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.
Hey, want to return to this question, as I wasn't able to fix it yet.
The Asset is a UnityEngine.Tilemaps.Tile and is not reset when changing its sprite manually in the Inspector.
This is not the case, however, when changing its sprite via the custom class, which holds it.
// public class TileSprite
[SerializeField] private Sprite _sprite;
public Tile tile;
public void Set(Sprite sprite)
{
if (sprite != _sprite)
{
_sprite = tile.sprite = sprite;
EditorUtility.SetDirty(tile);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
Tried to use as many methods as possible, but it doesn't seem to work properly now.
It seems that the Inspector saves the variable in the way not known to me yet
I don't see anything that would cause GunShooting to get a new configuration after picking up a weapon
i don't understand how GunPickupAndThrow.EquipWeapon has any effect, really
especially since you've got all of these naked GameObject variables floating around
It changes a sprite, and that's about it
well, it enables a sprite renderer
is GunShooting attached to each of these objects parented under WeaponSprites?
I see nothing in GunPickupAndThrow that even touches a GunShooting. How does the game figure out which GunShooting component to use when the player tries to shoot?
currentWeapon is private, so there can't be another component that does it
Player should have a field that stores the currently-equipped weapon.
Rename GunPickupAndThrow to WeaponHandling or something, and have it update that field when you pick up or throw a weapon
You could also do that (and change its type from GameObject to something more useful)
Part of the reason I've been pushing you to get rid of GetComponent is that it forces you to make your types more specific
GameObject doesn't really tell me anything when I look at it
it could be literally any game object
that's a given: everything "thing" in your game is a GameObject
It's more clear what your code is doing if it passes a Weapon, not a GameObject
i don't see how that's relevant to what we're talking about
I would get rid of that entirely. The weapon should have enough information to display the sprite and to set the shooting point
for example, it could contain a reference to a prefab
that prefab would have a WeaponVisual component on it
- Rifle Visual <--
WeaponVisual- Shoot Point
Instantiate the prefab and attach it to the player when you equip the weapon. Destroy it when you throw the weapon away.
This way, you don't have to have every single weapon visual stapled to the player
and you aren't trying to look them up by exact name
Show me a screenshot of your player's hierarchy, with at least one weapon unfolded so we can see all of the individual objects
(you can alt-click to expand all children)
no, I want to see exactly what you're doing
It will determine what this prefab contains.
okay, that's simple enough
This will be a single prefab.
It will be referenced by every AM9 weapon in the game
When you grab the weapon, you instantiate that prefab and attach it to the player
This way, you don't need to have tons of weapon sprites stuck to the player
You also don't have to get the name exactly right
This also means that two different weapons can still use the same visual
The prefab should have a component on it. I'd call it WeaponVisual
it'll be pretty basic
in fact, it could just be:
public class WeaponVisual : MonoBehaviour {
public Transform shootPoint;
}
When you instantiate the prefab, you'll get a WeaponVisual object.
You can then grab shootPoint from it
You can add more fields and logic to this component later, if necessary
then that's all the component needs to do!
Any time you're digging around in the hierarchy, consider replacing that with components that hold references to the things you need
I also have basically zero GameObject fields in my games
I only use a few, in places where I genuinely don't care what I'm referencing
(e.g. just moving an object to a position)
That would be more appropriate, yes
(every game object has a transform and vice-versa, so it didn't really matter there)
but Transform would better describe what the code is doing
I'm creating an airplane simulator and it has this piece of code:
rb.AddForce(transform.right * maxThrust * throttle);
here, maxThrust is set to 200f, throttle can be increased or decreased using space or shift.
The problem is; in flight if I reduce the throttle, the plane abruptly decreases its velocity. I want it to smooth over the change in throttling speeds over time and not abruptly.
How do I achieve it?
You could pass the weapon to the GunShooting component when it gets equipped
GunShooting can then read information from the weapon
(or it can just store the weapon and get information from it as needed)
It would also need to know about the release point. I would pass that to GunShooting as well.
It sounds like you only have a single GunShooting component right now, and that it's on the player. Is that incorrect?
okay, so if you do that, then the player should call methods on the GunShooting component of whatever weapon is currently equipped
That is reasonable, yes
The weapon contains the component that makes the weapon fire
if the config is just a bag of data, it can be a regular C# class
add [System.Serializable] to it and it'll show up in the inspector
you can then put directly into the GunShooting component
No. I am saying that GunShooting should contain the configuration.
I'm not saying to put GunShooting on the player. Keeping it on the weapon sounds fine.
the player should tell the weapon to fire
the weapon then decides what to do
Right. That component is responsible for picking up and dropping weapons (hence "handling")
Yes.
I wouldn't call it complex, but it's not trivial either. It makes you ask and answer some important questions about where your logic lives.
This is something you get better at as you design, implement, and re-design game systems
FBX files would be dragged into the project window
not into the scene view
ill try that, thanks.
i try to drag it into the project all prefabs window and it still wont import
ping me if you have a solution
In the first place you are trying to draga blend1 file which is a blender backup file. Not supported really but wouldn't be harmful
In the second case pretty sure your project window is in a search mode of some sort. Open an actual folder inside Assets and drag it in there
watch the whole thing I drag the FBX one too
I addressed that in my second sentence
Open an actual folder?
wdym
the project window has a file directory on the left
you're in one of those "favorites" searches or something
which isn't an actual location
you need to open the assets folder or a subfolder of assets to drag stuff into
Anyone know how fast is a HashSet actually? Tried finding online but can't. For example if I had a HashSet of 5 items and a Span of 5 items, could it be quicker to loop through the span to check if an item exists every time?
Those numbers are so very small that it would be of no consequence if it was faster to do it a different way, if you were to measure it.
Don't optimize until you're experiencing a problem or unless your N is probably > 1m or so
for N of 5, either way is going to be insignificantly different
How could I get the smooth movement of Rigidbody.velocity but the precision positioning of Rigidbody.position ?
When I do this the rigidbody goes insane,it does go to the correct spot after "settling", i tried also turning off gravity of each limb but didn't work..attached 1st gif
while (Vector3.Distance(body.position, final ) > 0.1)
{
body.position = Vector3.MoveTowards(body.position, final, 120 * Time.fixedDeltaTime);
yield return fixedUpdate;
}
this one gives a nice smooth transition but isn't always precise. gravity is off in 2nd gif , but on 3rd
while (Vector3.Distance(body.position, final ) > 0.1)
{
body.velocity = Vector3.MoveTowards(body.position, final, 300 * Time.fixedDeltaTime);
yield return fixedUpdate;
}```
Something like this?
while (Vector3.Distance(body.position, final ) > 0.01f)
{
float maxSpeed = 300;
float maxDistanceThisFrame = maxSpeed * Time.fixedDeltaTime;
Vector3 diff = final - body.position;
float actualDistance = diff.magnitude;
float distanceToMove = Mathf.Min(actualDistance, maxDistanceThisFrame);
Vector3 velocity = (diff.normalized * distanceToMove) / Time.fixedDeltaTime; // we want to move this distance in one physics frame.
body.velocity = velocity;
yield return fixedUpdate;
}```
there's probably a way to do it with fewer calculations but my brain did this as a first pass
This is more or less the calculation that MovePosition does, but by setting the velocity rather than using MovePosition
this is perfect! thank you.
genius with this lol
Thanks again! amazing
im not asking for optimization I'm asking for curiosity and not being able to properly benchmark that low of a number.
anyway yea someone gave me a benchmark and a span is like 1 nanosecond faster for 5 elements and 0.2 nanoseconds faster for 10, after that hashset takes over lol
for 5 elements, the overhead is going to far outweigh your measurement, so it's not really correct and you shouldn't use it as your Truth
You should probably just use whatever API surface is nicer/cleaner/less error prone
is there away to see static variables in inspector?
dont think so
they dont belong to any instance
No, static variables are not owned by an instance of an object so it wouldn't make any sense to show them on instances
In the inspector for what exactly?
The class?
there is no such thing
You could always use a custom editor I guess - but why not just use the debugger
You could technically write your own custom inspector for it to display the values on instances of the compinent, but what would be the point of that?
I just wanted to see if they go up, but i can just make another public variable that equals with the static but is much more mssy
Debug.Log
The inspector really isn't a debugging tool, no matter how hard we try to make it one
There's always OnGUI
would just log per frame or something, and collapse so if its the same it just stacks
or worse case a quick and dirty bit of UI that shows it
I use OnGUI to show bits of information
my main project has a very elaborate debug menu that's all IMGUI based
i m trying to transform a text in a string and i get this error: "Predefined type 'System.String' is not defined or imported"
use string instead of String
Show the full !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.
are you trying to interact with a canvas?
i'm using TMPro.TextMeshProUGUI usually
yeah that ^ is the class for the ui text component
i m trying to transform the int into a string and change the text basically
that doesn't answer my question
change the text of what? is it an element of the canvas
yes is a text
TMP_Text covers TextMeshPro and TextMeshProUGUI. It is a parent of both types.
yeah i almost always use TMP_Text and can always set things fine
without knowing what the error is, I can't say very much
the error
...huh
did you upgrade to Unity 6 Preview, or is this a new project created in 6 Preview?
is the error only in your ide?
oh yeah, that's the first thing to consider
really sounds like its references are just buggered up
I have this very odd problem where the rigidbody of the RaycastHit turns null after literally just passing a != null check, any ideas why this can happen?
if (Physics.Raycast(FirePoint.position, FirePoint.forward + inaccuracy, out RaycastHit hit, FireRange))
{
if (hit.rigidbody != null)
{
hit.rigidbody.AddForceAtPosition(FirePoint.forward * FireForce, hit.point, ForceMode.Impulse);
if (hit.rigidbody.TryGetComponent(out Damage damage))
{
damage.TakeDamage(FireForce * 50f);
}
if (hit.rigidbody == null) { // this is true during debugging sometimes
Debug.Log("hit.rigidbody is null??");
}
Debug.Log(hit);
Debug.Log(hit.rigidbody);
if (hit.rigidbody.TryGetComponent(out Human human)) // <!!! null exception on the rigidbody?
{
Debug.Log(human);
}
}
i said that upthere
anyways do you have a ideea i tried lookin in the unity6 manula but can figure to find something
perhaps TakeDamage did something
is TakeDamage maybe doing that
does it destroy an object?
good point, checking that
it indeed Destroys but i was thinking because it happens at the end of the Update() it shouldn't matter, but it does
Thanks i just saved and it works in editor i guess
close your ide, go into the unity project folder and delete all the sln and csproj files
feels like something is buggered up in them and having them regenerated could help
i often get mixed up with the triggers and collision events, is it good practice to queue these and handle them in Update and FixedUpdate only?
Hello i need help, I try to do that my player slide on the wall :
if (isSliding == true)
{
rb.velocity = new Vector2(rb.velocity.x, Mathf.Clamp(rb.velocity.y, -wallSlidingSpeed, float.MaxValue));
}
I know that isSliding is true but my player drop on the floor normaly, my rb.velocity is false ? (the if is on void update)
what about this?
if (isSliding == true)
{
rb.velocity = new Vector2(rb.velocity.x, 0f);
}
(or actually i would try something like this:)
if (isSliding == true)
{
rb.addForce(Vector2.up * -Physics.gravity, ForceMode.Acceleration);
}
Hey folks, so I need to spawn an enemy but after a specified delay. How would you go about doing that? I have a coroutine that Im using currently with a yield new waitforseconds but I feel like that is a bit inefficient performance wise?
That seems like a valid use of a coroutine to me. Also try looking into Awaitable, the syntax is nicer imo
There's no performance problem with a Coroutine
Don't prematurely optimize
Will do. Another question, i read that yield return new waitforseconds internally checks every time to see if the scaled time has passed but does that mean the thread is just waiting on this function?
no threading unless you use the Job system of C#
If the thread was waiting the game would be frozen
I wanted to apply best design principles
You asked about performance
There nothing wrong with the coroutine
Wait the coroutine doesnt work on a seperate thread?
my general rule of thumb is, if you do things in Update or FixedUpdate especially, try to limit "heavy" calls like Coroutines and GetComponents etc, otherwise its pretty moot in terms of optimizing
Fair
if you are familiar with javascript, its the same "async", as in, it just keeps looping and checking a condition, if the condition is hit, it will continue, otherwise it will skip it, perform another Update ad infinitum
Got it thanks!
Unity is single threaded unless you specifically create new threads or use the job system
Got it thank you! Appreciate the help!
Unity coroutines are -- if we strip out the special things like WaitForSeconds -- basically this:
List<IEnumerator> coroutines;
void Update() {
coroutines.RemoveAll(coroutine => !coroutine.MoveNext());
}
i have an abstract Entity class, i want to instantiate a gameobject depending on the child class, is that possible somehow? a public abstract GameObject(); or something that i can overwrite in the child class
depending on the child class
would be the child class' responsibility then
okay so how would i implement that?
...normally?
sorry are you saying what i stated isn't possible to do within another class?
say a class that holds a list of entities and needs to instatiate them depending on which child class it is
no, im just not sure what you're stuck on, this just sounds like normal subclassing
ah, you would just have something inherited to set that then. maybe a method subclasses can overload or just a prop they can set
like a public abstract GameObject GetGameObject();?
sure, might need to be virtual, not sure how c# deals with that exactly
right yeah ty i'll experiment 👍
An abstract method is automatically virtual
yeah Abstract is virtual but has not implementation so it forces the extending class to implement it
I find it odd that you need such functionality, do you plan on never serializing values for this class?
I guess I could see some use case for it actually but what objects are you creating? Could you not just use a prefab if all you're returning is a gameobject
Because overriding methods here doesnt really seem needed
wouldn't it save me from going if(Entity is EntityTypeA) Instantiate(EntityTypeAPrefab?
for every child type
That wasnt the suggestion at all. I mean could you not just have a public field for the prefab in the base class and plug that in inspector? Then whatever script does this code could just Instantiate(Entity.somePrefab)
Because from what I understood, it looked like you were going to construct a new gameobject in that method (then likely add components). Unless a lot of the components added are conditional, I dont see why this cant just be a prefab
oh i see can i have a public field for the prefab in an abstract class? if so that does definitely sound like the better option
and no i was going to fetch the prefab within the child class, not contstruct it within the function
I see, yes the base class can just have the field and every child class will have access if its public or protected
that is not a field, its a property and you can have both virtual or abstract properties
yea ik i was saying i can't have it just be a field
ah my bad
all good
implemented it, this will be useful if it works, ty :)
yes you can, no errors here
public abstract class AbstractClass
{
public int a = 5;
}
oh true just don't mark it as abstract
think they meant you can not override it, but there is no need to override since you can just give it a new value in the constructor instead
since its just a field
if its really wanted to be abstract so the extending class "must" define it, yeah just use a get only property on the abstract side then do something like
public override int a => 5 on the extending side
right true that's probably better for my purpose
now i remembered one thing i was trying to solve but ended up sidetracked with: is initializing different Entities based on their EntityData, since EntityData is not an abstract or interface and all Entities have it
enums for each type is an obvious solution but is there a more elegant way of doing it?
also what do you want to differ in the extending class, like if its just a few field, and nots not how methods or properties work
why even go abstract
like if its all based on entityData and that is its own thing just sounds like you just want to construct things iwth EntityData passed in
{
public abstract EntityData EntityData { get; }
public abstract void InitialiseData(EntityData entityData);
public abstract void Initialise();
public abstract void Tick();
public GameObject Prefab;
}```
this is the class rn does that answer the question or do you want me to explain the class's goal?
yea true
but i want to act on the data in different ways
and i might move on to making the data abstract too if i need to
what is EntityData type wise?
rn a Vector2Int and DataCollection which has two lists of data objects that are filled with different values depending on how they're initialised, so it's pretty modular
ok but on a regular C# class or Struct, or extending from MonoBehaviour or ScriptableObject
ok so just make that non abstract and a field
you already have a to pass it in via the InitialiseData call
also would question if you want a whole new ENtity type for each of Entity data or not,
or is just have Entity be non abstract but difference instances setup with different data is enough
is that better than how i have it now? what's the difference between that and having it my current setup
public class EntityType : Entity
{
public override EntityData EntityData => data;
EntityData data;
}```
yeah i don't see a need for it right now but maybe i will in the future
what is this trying to accomplish though
like you want everything to have EntityData so why have it abstract
its not like you need to change the implementation of how its got
not everything has to be abstract in a abstract class
also do not make guesses about what you will need in the future untill you have a concrete idea of what is needed then
just make stuff that works for current cases and is easy to understand
you can change it in the future if needed
true true
i just wrote it that way idunno
rn either way doesn't really matter
do you have an idea on how to differentiate between EntityData like i mentioned here?
will EntityData ever be shared?
like maybe a good way is EntityData is a ScriptableObject and each EntityData type lives in your assets folder as a asset
then you can just use a serializedfield and drag on the one you want
yes it would be shared and changed a lot, scriptable objects wouldn't work in my case
why is that
otherwise really the option is to make all the EntityData's in some central place in code, and loop and pass it to each Entity that needs it
cause the game doesn't work if data isn't persistent and mutable
yea that's what i was thinking, the Cell class that holds the list of entities takes in a list of EntityData and initialises different entity types based on the data, it's that last bit i'm thinkin on rn
Part one: What happens when the battle scene first starts/opens?
1. Scene starts
2. Character Intros/Cutscenes
3. Start someone's turn
Part two: What does a character's turn look like?
1. Activate the AI Module of the character whose turn it is
2a. Player-controlled AI open a UI to choose things.
2b. NPC AI use their brains to choose things.
3. Actions chosen are executed.
4. When they're done, they can choose to end their turn, once their resources have run out, or for whatever other reason.
Part three: What does the overall combat state machine look like?
1. Opening (When done, go to 2).
2. Character Turns (Repeat over and over, switching between characters).
3. Victory or Defeat (When victory or defeat conditions are met.
Are there any ambiguous parts here that I should plan out more clearly, for designing my turn-based combat system's state machines? Right now, I'm just doing the overarching planning, rather than the actual details.
can shootpoint bone name be determined in script file ?
looks good
im trying to have an animation as a transition in a scene
and it works in other scenes
but specifically not this one
idk what to do
{
_angle.y -= _lookAction.ReadValue<Vector2>().y * rotationSensitivity;
RobitTools.ClampAngle(ref _angle, floorangleY);
}```
Trying to add a limit to how low the camera can rotate vertically but got hit with an error like this.
I'm unsure how to add in the floorangleY limit for ClampAngle.
well it seems like this ClampAngle method you are using does not take 2 arguments
Yeah, I know. I'm trying to find a way for ClampAngle to take 2 arguements
im so confused 😭
Or at least stop when a certain angle is reached.
well it seems like it's one of your methods, right? so just write an overload that accepts two arguments
Overload?
no
Huh
Can I overload even if all of my functions are floats?
Or do they needed to be doubles to make it work?

Ok
Hey guys, I'd really appreciate some coding advice.
I want different audioclips played depending on what objects you click on.
Should I create an audiomanager and instantiate audioclips through it, or can I just add AudioSource to each of my gameObjects respectively and just use AudioSource.Play?
I'm asking in terms of better performance, I'm still a newbie so I don't know best coding practices
Doing it through some audio manager will be better, since you'll be able to pool the audio sources. But you'll still need some way of deciding what clip to play then
each object will have a script assigned to it anyway (for other effects) so I will just assign clips respectively from there. Thank you for the advice!
I've never really done pooling before but I will figure it out
you might not even need pooling. you could have a single audiosource on the script responsible for playing these and use like PlayOneShot, i guess depends what you're doing with these
Don't ask to ask, post your question in here and somebody will get to it when they know an answer.
I see! I've been reading up on pooling just now and I think the suggestion you provided will work better in my case (it's a simple 2D hidden object game where each found object plays it respective sound). Thank you
if i have an abstract Entity class with EntityData, and i want to spawn the correct Entity subclass depending on a variable in EntityData, what would be a good way do to that?
Your abstract class has a variable that indicates what inherited class should be spawned?
Can I ask what you are trying to do specifically that requires this?
i'm trying to spawn and initialise Entities from savedata, the savedata consisting of EntityDatas
a load function basically
Hey guys someone an idea/hint?
Are you sure that's 2.8 and not something like 2.809494e-9 < scientific notation which is essentially 0?
Because it looks directly in the middle of the range aka about 0
And the way you're doing that Lerp it's not really going to exactly reach the desired values since it's a "wrong/lazy lerp"
Guys, if I have an object which is inside a circle, how can I find the nearest point (to the object) that lies in the circle's circumference?
Relative to that object's center?
yeah
Make a line from the center of your circle in the direction of the target with your circle's radius as the distance.
what would be the target in this case?
The object inside the circle.
Yes for circles and points
a = center of circle
b = center of object
r = radius of circle
direction = (b - a).normalized
answer = direction * r```
this should work, I believe:
Vector3 GetNearestPointInCircumference(Vector3 center, float radius) {
Vector3 direction = transform.position - center;
direction.Normalize();
direction *= radius;
return direction;
}
you beat me to it 🙂
thx!
The answer would be a point on the circle's circumference nearest to the object's center.
yeah
This would work for objects outside of the circle as well.
Do note though that you may get undefined behavior if the object is at the center of the circle - there isn't any direction if the object is at the origin of the circle (ideally, it would be equal distance from any point on the circumference of the circle)
apparently it returns a position in the circle's circumference who's position is the origin
Which object is this script on?
Direction would be defined as (target position - initial position) normalized
So if the center variable was referring to the target, it would be (center - transform.position)
I thought you meant otherwise
let me try
now it's strange
the debug code, btw: ```csharp
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawLine(center.transform.position, GetNearestPointInCircumference(center.transform.position, radius));
Gizmos.DrawWireSphere(center.transform.position, radius);
Gizmos.DrawSphere(GetNearestPointInCircumference(center.transform.position, radius), 0.5f);
}
You may want to use local position if you aren't wanting to account for parental offsets
but they are both children of root?
This looks fine
yeah
I believe I have to add the center's position to the return
and use the original code (i.e. before inverting)
Yeah. The initial result did not account for the circle not being at the center of the world - you'd just add the circle's position as an offset to make it relative to the circle's position.
it works now, thx!
do you mean gameobject or scriptable object
those are two different things (I believe)
oh
They're different tools used for different things.
normally I'd split functionalities between different scripts
Where SOs aren't expected to be mutable.
but if the game is small or has little functionality for each object, I think it's fine
And MBs are associated with GOs as components
uhmmm, I think that is too much
Something to consider (not taken seriously though)
<#archived-code-general message>
yes
This will become an unmanageable disaster in anything more complicated than flappy bird
Like I said, unmanageable disaster
the entire point of components is that you can compose them
you can combine them to produce more complex behaviors
Can unity show a dictionary in the inspector?
I'm asking because it isn't showing it to me
it's a dictionary of a enum to a struct
both have [System.Serializable]
https://paste.ofcode.org/fH8srXsqbTMKs8sqryTqy2 so iam generating a area with blocks(stone) then changing them randomly and replacing them with ores(eachone has a start and end spawn height) but in the code when i rmove the waitforseconds(.3f) it spawns a kind of platform inone height only. And when i put the waittime it exits as it should
You are right I think, but I tried with a normal lerp tho. Also the 2.8… does look like the value is 2.8 which totals fucks up the lens. What would be your suggestion?
for the code I believe nothing should change if it's 2.809...e-9
No. The Unity serializer cannot handle a dictionary.
oh
There are "serializable dictionary" assets you can use
they're a bit jank from my experience
I guess I gotta figure out another way to debug
Has anyone successfully created a properly-working serializable dictionary? It seems, the custom Editor can only be used for a class with a single generic parameter, like in the case with List, but not for 2
You have to derive a specific class
public class IntFloatDict : SerializableDictionary<int, float> { }
e.g.
that was my experience when I used one of those packages, at least
You have to either create your own class with a Key and Value or derive from the Dictionary and create a custom Editor for it. Both with Serializable attribute
WDYM by "normal lerp" - and show the whole value and what it's being used for
I see, you still cannot serialize one without an additional class
You don't need to derive a concrete type, remember! Unity supports generic serialization.
I have mentioned above that only for a single generic parameter #archived-code-general message
Dictionary contains a T for both key and value
So I don't think you can create one for it
I have to create a custom Editor in both cases?
well it did just work for a class with two type parameters
I am very sure that I recently ran into a situation where it didn't work
so I'm confused in both directions!
What do you mean?
public class Test : MonoBehaviour
{
public EventPicker<GenericQualifiedFMODEvent, GenericQualifiedFMODEvent.Criteria> nuhUh;
}
enjoy my very long type names
Not a smooth damp I meant, let me be more accurate when I’m home. Thx for your time, you helped me before tho 🙏🏽
No way. How have you done this?
What makes you think it doesn't work with more than 1 generic parameter? Generic serialization support was added back in 2020.1, and there were no limitations on the number of parameters then.
I wonder if I got confused because I tried to serialize an abstract class
public SecondOrderDynamics<float> oops;
yeah, that's an abstract class
of course it didn't serialize properly
I've had a remarkably difficult time shaking this lmao
It seems you can create a custom Editor for a single generic parameter this way, with <>. But I don't think it's possible for 2?
CustomEditor(typeof(MyClass<>)
#archived-code-general message
Although this is a property drawer?
Oh, well, I've only been talking about the support in the serializer. I'm not sure about custom editor support.
What do you mean by the support in the serializer?
Isn't that what a custom Editor is?
could you show me how?
No. Custom editors decide how things get presented to the user, but can't change how things get serialized.
No, if you create a struct, you'll only have to mark it as Serializable
Have you tried this with more than 1 parameter? The <> does not specify any number of parameters, it's open.
I see what you mean. I was saying you cannot display a custom class with 2 generic parameters in the Editor visually
Yeah, <,> doesn't seem to work
Although not sure whether you can just use "MyClass" without the typeof keyword for generics
You don't need the comma. Like I said, <> is not specifying that there can only be one parameter. It's saying that there are no parameters specified, so it's the open generic type.
Yeah, this way it also doesn't seem to work
Unity doesn't support it, I suppose
If you have no custom editor, are you seeing the default inspector for your type?
This is a separate problem.
If you see nothing, that doesn't mean the custom editor isn't working, it means the serialization isn't working. Because Unity will always display anything that is serialized with a default inspector.
Components can't have a generic type. They need to be a concrete type.
Oh, right. That's my bad. I thought you were using a property drawer.
No?
Unity doesn't serialize generic classes with the Serializable attribute
Which one are you talking about?
i just showed an example of it doing this #archived-code-general message
I'm confused now. Are you making a CustomEditor for a MonoBehaviour, or a PropertyDrawer for a serializable class? You can't make a CustomEditor for a serializable class.
yes, those are two totally different things
Simply create a struct with the key and value variables and Serializable attribute
and create a list of it?
This is an example I've taken from my code
[Serializable]
public class TileSpriteInfo
{
public TileSprite sprite;
public string name;
public TileSpriteInfo(TileSprite sprite, string name)
{
this.sprite = sprite;
this.name = name;
}
public override string ToString() => $"({sprite}; {name})";
}
Yes
ok, thx!
I do something similar to save my game settings
[Serializable]
public class FloatSettingValue
{
public FloatSetting setting;
public float value;
}
I could actually serialize dictionaries with Json.NET, but this wound up being more conveinent anyways
Have you simply marked your generic class as Serializable?
Yes.
https://gdl.space/olucixocet.cpp
This is the entire EventPicker class
again, this has nothing to do with a CustomEditor. You were trying to write a CustomEditor.
a CustomEditor is used to create a custom inspector for a unity object
I see, this class is serialized properly
[Serializable]
public class Test<TKey, TValue>
{
public TKey foo;
public TValue bar;
public Test(TKey foo, TValue bar)
{
this.foo = foo;
this.bar = bar;
}
}
Maybe that does work if you write a CustomEditor for Foo<> and then create a class that derives from Foo<Bar>. I haven't looked at that
For some reason, I thought it was impossible since it's not possible with the custom Editor

they are not.
How to remove Gradle error.
By fixing what the gradle says is the problem.
This is a code channel, and your question isn't code related. #📱┃mobile
I fixed it but when build it's giving the same error dialog box in unity.
Just curious, what would FloatSetting contain here?
FloatSetting is a NamedIdentifiable, which is an Identifiable, which is a ScriptableObject
Identifiable copies its asset GUID into itself
I have a custom converter for Json.NET that serializes an Identifiable as its GUID
To deserialize, it asks the IdentifiableRegistry to give it the object that corresponds to the GUID it just read
I load all of the relevant objects into the registry on game start
the serialized float settings look like this
{
"setting": "746195CFEFACF4F21B28F1B7582420E6",
"value": 80.0
},
{
"setting": "62774F12EDF4B4363BEAAFF33E1B04BA",
"value": 1.0
},
{
"setting": "C7BDEBFD74B7F4747A85D455C77E22BC",
"value": 0.4
},
Some code?
ok!
Hey, I'm having some difficulty cloning an instance of an arrow prefab.
I've tried a few things but it still doesn't work.
I've tried directly referencing the field, but that adds the component to the original prefab, since usedArrow = newArrow, and doing addComponent directly alters the original instead of an instance.
I've also tried creating an instance then turning it off, but the code seems to break because the arrow self-destroys even when disabled (has ontrigger event/coroutine on start). Meaning the "created template" gets self-destroyed before it can be used by the bowObject. Plus it tries to execute the arrow as if its a normal arrow, rather than a template in memory.
What I'm trying to do is create a prefab object in memory, where it can be used as a reference rather than a scene object which executes. I want to clone the original, then modify the newly created object, then inject that into a field which the bowObject will then use as the "real arrow". The bowObject will never reference the original prefab, only the modified one which is created at runtime.
The idea is that when you level, you get different perks that get applied to the arrow. The idea was to avoid creating a ton of prefab variants with custom scripts on it, and instead make these modifications to a clone at runtime when something like a LevelUp() or OnStart() event is called.
Additionally, the reason for having a custom field is to avoid spamming addComponent everytime an arrow is created, and instead grab from the modified template, so this operation is only called once. Meaning all the heavy lifting is done initially in CreateArrow() then the field is just referenced
Any ideas on how to create a copy of a pre-existing prefab in memory, modify it, put it in a field, then reference it, all without spawning it in scene? ChatGPT seems to suggest the "instantiate then disable" but then you only spawn disabled arrows...
You can always enable it after spawning
is instantiation the only way to create a template? Or is there another method to safely create a copy in memory only?
when i say template, i mean copy over the rigid body, collider, the script and any other info from the original object which would be spawned in scene
Sounds like you're wanting to create a new instance of the prefab, which is what instantiate does. You aren't wanting it in the scene which implies you'd want it not active.
but can instantiate be ran without spawning something in scene?
Just modify the new instance after instantiating the prefab.
Then you'd just copy/clone the instance and have the clones be active etc
Ya I am, i seem to be misunderstanding something. Since when i instantiate and modify it, it'll try to execute the code.
Even when I do instantiate the arrow and turn everything off/disable it, for some reason when I spawn a bunch of disabled arrows, when I touch one the reference arrow gets destroyed and the bow fails to see any arrow
something strange is happening
you know you can modify the prefab before Instantiating it and the new clone will have those modified properties
Ok, it sounds like the only way to create things is to actually spawn them in scene, then turn them off, so that it physically exists as a reference
I don't see why you need to create a new "arrow template".
Set each arrow up the way you need is as you create it
I guess it'd be nominally more efficient
You surely aren't wanting to create new assets during runtime 🤔
Ok, sounds like i have a redundant field based on what ya'll are saying which makes sense
I'm trying to avoid operations like spamming add component every time a bullet or arrow is fired. maybe it has 12 components per arrow or 50, i'm not sure. but the idea was to create it once then reference that new modified arrow
is add component cheap?
just instantiate a prefab every time you need it
Additionally, the reason for having a custom field is to avoid spamming addComponent everytime an arrow is created, and instead grab from the modified template, so this operation is only called once. Meaning all the heavy lifting is done initially in CreateArrow() then the field is just referenced
A few AddComponent calls are completely fine. I'd rather have that than deal with the oddities of trying to make "fake prefabs"
Just create variants for your prefab if the components differ else modify fields and whatnot of the new instance on spawning.
it sounds like there would be a very large number of prefab variants
e.g. 10 components, pick any number of them
yes, i'm trying to forward think so i don't get boxed in
it's just there's some technical strangeness with the methodology that i'm trying to work out
I'm following the suggestions, just trying to confirm it. because ya add component everytime instantiate is called would be easiest
I usually do mod = Instantiate(something, transform), then mod.DetonateObject(5); etc etc
Can you give an actual example? This seems unnecessary.
ok sec, gonna modify my current code to remove the redundant field
[Header("Template")]
public Projectile arrowTemplate;
public Projectile usedArrow;
[ContextMenu("Create arrow")]
public void CreateArrow()
{
// Take template, then adjust, then set as active arrow
var newArrow = Instantiate(arrowTemplate);
newArrow.enableArrow = false;
// add ricochet spell to arrow
var comp = newArrow.AddComponent<RicochetArrow>();
comp.SetProjectile(arrowTemplate);
// assign the template reference...
usedArrow = newArrow;
Debug.Log("Updated arrow with new stats!");
}
the bow object just uses a getter function which returns "usedArrow" so it knows to use the runtime version of it
The bow just calls this
projectile = PlayerEquipment.Instance.GetArrow();
Instantiate(projectile, TransformsManager.Instance.arrowLoc.position,
Will the create arrow method always create an arrow with the ricochet component?
at the moment yes, it was just a test
i would have a switch that picks what component stack to add once i create that code
Assuming you aren't hard coding this for every combination, maybe just create a prefab with the component already attached?
thats what i wanted to avoid because i don't know how many components i will have
i wanted to automate that
If you can't meaningfully set up the arrows ahead of time, then I'd just go ahead and use AddComponent each time
Especially since this isn't going to be happening dozens of times per frame
I can't imagine that AddComponent is that much worse than instantiating something with the component on it already, either
true, the AC would be once on creation. if its relatively inexpensive thats the go to
but to confirm, you must instantiate an object turned off in order to create a template that can be referenced?
there's nothing special about it being turned off
you can instantiate whatever you want
I believe that makes sense in the context of mono. since mono objects must be attached to physical game object
if you want to prevent Start from running, the relevant behaviors must be disabled
or the entire game object must be deactivated
ofc, i placed the actual code in a function ActivateArrow() and put a bool return on the onTriggerEnter to prevent the arrow from activating (has to be manually activated)
ya i did a enabled = false but ontrigger enter seems to run, but when i added a !isActive bool it blocks that strangely enough
i do cache the instantiates into a local variable then modify them for sure, it just seems to be acting up here and there for some reason
but it sounds like I have two options, and indeed I do need to instantiate (there is no non scene instantiate operation like new() that would put it in memory)
Just have the object inactive?
yep i get that, just confirming at this point
Enable would only be referring to the specific component
true, i've done both. enabled = false and gameobject.SetActive(false)
i'm tellin ya something is off on my end. but thanks for the info just wanted to confirm the options
btw, why doesn't new() work?
new what?
From what i've tested, it just creates a new class object, but it doesn't create an actual prefab in memory like i was hoping
like var arrow = new Projectile(); arrow.ActivateProjectile(5) for example
You are not allowed to construct new Component objects