#archived-code-general
1 messages Β· Page 121 of 1
then why would i use list?
because you can only change it once within the inspector
cause you can modify it at runtime?
only during edit time
not game time
lists allow you to modify the length during game time
This isnt a bad appraoch, I recently coded an interaction system using interfaces similarly to this
gotcha ty π
sure
Will the food interact differently depending on whether the player or the cat interacts with it? Will the player or the cat know that they are interacting with food specifically, and thus play a specific animation?
- Yes, they respond differently
- I'm not sure what exactly do you mean. (re: animations. If player and cat respond differently, animations can be handled there)
think I found this solution
Vector3 targetPosition = target.position;
// Set the x position of the target to match the WeaponAimEndPoint
targetPosition.x = weaponAimEndPoint.position.x;
// Calculate the direction from the aim point to the target position
Vector3 direction = targetPosition - weaponAimEndPoint.position;
// Apply the rotation offset to the direction
Quaternion rotationOffset = Quaternion.Euler(0f, weaponAimEndPoint.rotation.eulerAngles.y, 0f);
direction = rotationOffset * direction;
// Calculate the vertical angle based on the transformed direction
float verticalAngle = Vector3.SignedAngle(weaponAimEndPoint.forward, direction, transform.right);
I think composition is the approach, otherwise you're going to end up parsing stuff like like dalphat was saying.
assuming you want a unique interaction depending on who interacts with what
Could you elaborate on that implementation a little bit, out of curiosity?
Thereβs a certain amount of hard code associated with mine, but not exactly hard coded decision making(?), it takes inspiration from the IComparable Interface
class Cat : CommonBase
{
void Update(){
interaction.Interact(this);
}
}
class Enemy : CommonBase
// same as cat
class Food : Interactable<CommonBase>, Interactable<Cat>, Interactable<Human>
public void Interact(CommonBase a) //do nothing
public void Interact(Cat theCat) // decreases food, and tell theCat to play eating animation?
implements ?
oops
thought some new hip c# keyword
java brain 
yeah I was still figuring it out in my head
C##
im trying to map light cookie to shadow an area, and instead of eyeballing it i want to grab the lights internal render
any pointers would help
C#β
all i see is command buffers
Technically that would be Cx (double sharp)
sounds pointy
- I eventually did the same bu the other way around: Interactor<T> where T : Interactable. Now that i'm here, how can i store those in a collection? I try to use base interfaces Interactor<Interactable>[] but it refuses to cast my types
you need base interface
- I already have one
- Ah. Alright, but i'm afraid i'm not following. How would that work?
- If i do this, i lose any .Interact() accessibility right?
you will have to cast
you can also create a non generic base method that calls the generic one casting from object to T
you will have to cast in any case, you can avoid having base interface by storing object[]
- Well one object can implement however many interfaces with different generic types
yep
you cant weasel out of this, its the way generics work, they are compile time and generate unique types, so you either have to cast at runtime or not use non generic collections
Pumpkin's way seemed ideal, since you wouldn't need to know the type, you just method call, right
but if you were to do it like this, I'd assume you have to specify what type it is to call that functionality, yeah?
ah ok
you can type match, you can preconstruct generic types and use them to cast with Convert.ChangeType(input, typeof(T));
but in general a generic implies the types are known at compile time, in other words the intended way is to hardcode things that use generics
deviation from that lead to the realm casting
Hey everyone. Not sure if this is the right channel to ask this, but: how to i create a blur UI effect on Unity? I want to achieve something similar to these images for a pause menu and i want to know how to create one (i'm using Standard RP). If it's performance friendly, the better π
- Alright, no collections then. I'll report to my customer and see what they say about it. Thank you everybody for your time and effort
plenty on asset store and github
"ui blur"
I'd prefer if they were free, if possible.
then look for free ones
there is a toggle "free assets"
and github is generally foss
I've already tried several of them, but they have either of those issues:
- They don't work with Screen Space Camera UI
- They don't work with Unity 2022
- They have a massive performance cost
So if anyone knows a better alternative, free or not, i'd appreciate that
time to shader graph
background blur can be pretty performance intensive.
a lot of times you can cheat it by having a blurred image that you set as your background instead of actually blurring the current background
Mmmm, i guess, if there is no other option
Thanks anyway π
best way to compare performance really
Hey, i have a reference to this RectTransform of the canvas, but how do i get the scale of this? it always return 1 for what i try
bit of a late reply sorry.
I had three structs and two interfaces. first structs were TaskDataIn and TaskDataOut, where in has a caller and callee GO, and out has a string[] info and a bool success
First interface I called Soldier for lack of a better name. It has a public TaskDataOut DoTask(TaskDataIn data, string taskName) so that way one soldier class can do multiple things depending on the task required
Third struct is a Command which has a string name, a string task, and a list of Soldier to run the tasks on. It also has a TaskDataOut[] DoTasks that returns the TaskDataOut result of calling the task on every soldier in it's array
last interface is Commander. it has a Dictionary<string, Command> commandList.
Example of why I need this complex setup: A button panel with 4 buttons(Commander) where each button can be configured by the player to do different things (like open a player made list of doors(Soldier with open, close, and toggle tasks), or turn on a player made list of lights(Soldier with on, off, toggle commands) )
although its flawed in that it can only handle discreet data, I'm working on modifying it to handle something like the height of a lever change the brightness of lights without sending a discrete set brightness command
what for ?
the scale isn't relavent cause the width/height always changes
i wan t to instantiate 10 object between the 2 side of the screen but it don t work good without the scale i guess
use this probably
https://docs.unity3d.com/ScriptReference/Screen.html
it s not about the canvas?
canvas has to do with UI sutff, if you want the screen width/height use screen class
i wan t to use just UI i guess
Thank you for the extensive extensive reply! I'd like to play around with writing such a system just to explore the idea a little further, and I keep hitting little stumbling blocks... the insight into your approach is much appreciated π
How can I check in the code if a ScriptableObject variable is of specific type?
If I have SO: Enemy and I create 2 enemies: Zombie, Skeleton.
How can I tell in a script if:
EnemySO enemyData;
enemyData == Skeleton
Without adding enums to the SO or any kind of uniqueID if that's possible.
if(enemyData is SkeletonData skeleton)
you want to compare the data references?
Perhaps that's a bad approach.
What I want to do is simply count how many instances of a specific SO I have.
In a script
at runtime or editor time
runtime game.
alright, you can make a dictionary of lists, or ints
I want to count how many skeletons and zombies I spawned.
yes
But what do I use to count them?
if all skeletons share the same data reference then you use the reference
Skeletons and Zombies both are created with SO called EnemySO
is it the same object in editor?
Each skeleton/zombie is created by:
List<EnemySO> enemyDB = new List<EnemySO>();
void Start()
{
// loop 20 times
SpawnEnemy(Instantiate(enemyDB[0]);
SpawnEnemy(Instantiate(enemyDB[1]);
}
Above means I have 20 skeletons and 20 zombies.
im asking is it the same object in editor
so separate assets for skeleton and zombie
separate scriptable objects
sharing same type
What's wrong with enum or type id?
Yes, is there other way of doing it?
If I create 20 skeletons that share SO, wont they share reference?
Each time I want to add new enemy I'd have to open a script to add new enum value.
Not good if non programmer wants to add new enemies.
But there is no reference, each skeleton is unique.
I throw guid's on all my SO assets
so you are duplicating EnemySO at runtime?
i dont understand, you have a prefab, the prefab references SO, 20 skellies will reference the same object as a result
Yes
why?
defeats the purpose imo
I dont want to share it.
The problem with guid I had is that if you copy paste SO file it will copy guid as well.
Is there a way around that?
@potent sleet ah yes what i need is just the width of the canvas but when i put the anchoredPosition.x to the width/2 it is at the right edge
generate one on awake ;)
ah
assuming you're creating instances I guess
you created a problem, for no reason, you are mixing immutable design time data with runtime data, losing so much good practice opportunities, for no reason
I probably use SO wrong.
But SO is basically a class that you can edit in the inspector.
Then I make copies of it.
Prefab is just for the sake of having a skeletong sprite + animation.
Prefab also gets a reference to the SO that created it.
What do I need to do then?
reference them
Then I have to make a copy of all properties in another class right?
I wanted to avoid that
i.e. when you need to know what is the skelly damage you do data.damage, from monobehavior that references said data
I do SO duplication for some objects, but this is more being lazy and not wanting to couple it with an identical class
But perhaps that's how it's meant to be done.
you dont need to copy anything
Exactly π
just directly use data for read only ops
I mean...you are not wrong, I am not changing all the data, but there are cases when I do.
I have weaponSO which can level up so I change all properties of it on each level up.
If I have to make exact copy of a class so I can change the data at runtime it's just a pain.
instead of that you can define specific SOs for leveling up
again, read only at runtime
Its basically as Mao said, It's me being lazy.
what do you mean define specific SOs for leveling up?
my debuff/buff class is actually pretty sweet considering how lazy I made it (also an alternative to the serialize reference way)
literally ItemLevelUpData : ScriptableObject that contains set of modifications to apply to weapon based on level
The level up is using regular class, but its stored in SO
shove those in a list of possible level ups
public class Stats
{
int strength;
int dexterity;
//etc
}
public class weaponSO: ScriptableObject
{
[SerializeField] public Stats stats;
public void OnLevelUp()
{
stats.strength += 1;
}
}
This is simplified version of it.
I don't need SO for Stats tho right?
Regular C# class works fine.
depends on your impl
impl?
problem here is you are mixing runtime with edit time
Yeah, but why does Unity allow me to Instantiate SO if it's bad?
Do I really have to make copy of weaponSO as a regular class just so I can work with it at runtime and make copies?
you can yes but then there is no clear distinction between the two, and hard question arises - why arent you using MonoBehavior
for its intended purposes
Monobehavior stores instance of WeaponSO as it's member.
I do that Debug.Log(GetComponent<Canvas>().scaleFactor); and it always return 1 why??
if its stores a duplicate, you are doing the same thing twice
you already have a mono, that is supposed to carry runtime data
but on top of that you copy the SO
public class WeaponController: MonoBehavior
{
List<WeaponSO> weapons = new List<WeaponSO>();
public void UnlockWeapon(WeaponSO weaponData)
{
weapons.Add(Instantiate(weaponData));
}
}
Probably defaults to 1 since it's being scaled by another source
Right, so I have to copy SO properties manually into runtime(monobehavior) class?
Then each time I add/remove a property I have to update other class too?
only those that need it
in 99% of the cases data will remain immutable
read only, in rare cases like stats you have to copy over you can use any number of copy mechanism
but it s written that it s not 1
but the console says it s 1
I probably need to make stats into a dictionary with enums, but those can't be used with an inspector.
So it's hard to copy Stats class to another, unless done manually or through reflection(?)(I don't know much about that, but you can loop through class members somehow)
Ah, it's the canvas itself, I think you need it as world space to get the actual value
serialize/deserialize thats like most cloning works
That's probably why I went an easy way that didn't require manually cloning data.
But, I don't mind refactoring it at some point.
It was mostly for a prototype.
hein??? i dont think so
So I will make a runtime class for each SO I have and use SO as readonly.
What do you need the scale for anyway
yes for most cases SO just carries data your game code will read
references it directly
thats how you can distinguish what the thing is, despite there being 1000 of them
So I should keep properties readonly in SO right?(Not possible for some of the things tho)
Can readonly still be written to via inspector?
to place 10 UI gameObject on the screen on the bottom of the screen that are in the all bottom
Then you should be calculating the bounding box height and width, not the scale
"bounding box"?
depends, i do it for data safety, any changes to SO at runtime will persist, so its kinda mandatory if you work with more than yourself
i tried by doing the calcul by myself with the value showed in inspecter and it worked
Take Stats class for example
public class Stats
{
int strength;
int dexterity;
}
public class weaponSO: ScriptableObject
{
[SerializeField] public Stats stats;
[SerializeField] public readonly string weaponName;
}
thats not what a readonly property is
that is readonly field and its not how it works
That's why I Instantiate SO so I didn't, but it did happen even if I did that, because in some cases I forgot to Instantiate and actually changed SO data in a file at runtime.
public string WeaponName => weaponName;
[SerializeField] string weaponName;
oh
Don't remember the logic off the top of my head, but you need to calculate the rect transform of the canvas area and do the math by the height and width of it all
Thanks, I will see if I can use that.
you can also separate the serialized version of stats from runtime
which is what i do
since runtime stats are each a class, with lots of code attached to them, and serialized template is simply int/float values
Can you use 1 class Stats and have both readonly version for SO and normal version at runtime?
ah
got it
so I need a copy either way.
you can do something like
With just data.
I was hoping to do a Dictionary as that makes it easier to add stats from multiple instances(weapon stats + upgrades stats etc)
public class Stats
{
int strength;
int dexterity;
public List<Stat> GetRuntimeCopy()
{
List<Stat> list = new List<Stat>();
list.Add(new Stat(strength));
list.Add(new Stat(dexterity));
return list;
}
}
But you can't serialize it to show in the inspector, perhaps I should use regular class for SO and dictionary at runtime.
oh
That makes sense too, so I can return a Dictionary from this function instead.
yes
its also a very common pattern i use even have a few interfaces that automate some things
That will save me from having 20 functions that do exactly the same thing but for each stat(adding stat bonus for weapons + upgrades + other bonuses)
[field: SerializeField] public string WeaponName { get; private set; }```
Shorthand for that which I plaster everywhere in my SOs. You do lose your lower case variable if you were to use it anywhere in the script though.
that is inferior
I just couldnt afford to refactor it at that time, but this convinced me π
it serializes the value as <backing field>__something
What is the difference between
[field: SerializeField]
and
[SerializeField]
ah
It automatically makes the backing field.
you cant refactor public property name without using FormerlySerializedAs and so on
Ah, yeah I can see that
you cant easily transfer data from one serializer to another because the field names dont match
just don't make mistakes
it basically invites a set of problems you will pay for later
Alright, thanks for the help.
I will work on refactoring it in few days when I am done with other things.
Keeping SO readonly, and making a separate runtime class for the data as needed.
You can actually use formerlySerializedAs, but you need to add the extra syntax of the backing field in it all
within the string
gotta test it though cause that's actually something I do prefer working once I start populating my assets
im not saying you cant, im saying you have to, if you change the public getter
which in case of separate field you can keep its name forever the same, its largely irrelevant
Oh, I see. Yeah, that's quite a downside if you do like to change up your variables.
Hey people, I get the following errors when I try to install the "Netcode for GameObjects" package, anyone know what should I do about it ? is it a problem with my connection or is it something I need to do ?
[Package Manager Window] Cannot perform upm operation: Unable to add package [com.unity.netcode.gameobjects@1.4.0]: One or more dependencies could not be added to the local file system: com.unity.burst: aborted [NotFound]. UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
[Package Manager Window] Error adding package: com.unity.netcode.gameobjects@1.4.0. UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
the first error asks for the "Burst" compiler package as a dependency, when I tried to install that separately it gave me an error as well,
I deleted the "packages-lock.json" and "manifest" files and reseted my packages to default from the "help" tab and it didnt help.
any other suggestions would be helpful.
you have experimental packages enabled?
netcode one you added through pm or through manifest edit?
is there a way to disable or circumvent frustrum culling on a SpriteRenderer? google is only giving me solutions for meshes. i have a shader that's moving vertices around and the object is dissappearing when it's old position rather than new position is offscreen...
It should be the same solution for SpriteRenderer and MeshRenderer, because both inherit Renderer, which has the bounds property you need to modify to contain your moved vertices.
oh okay, I think that's all I needed to know to figure out the rest, thank you!
Hey! I want to have the damage that was done to an enemy displayed as text that moves with every enemy. I have a version in TMP(TextMeshPro) that's displaying the damage but it's locked to a single point on the game canvas and not moving with the enemies like I want it to. Can this be solved with TMP or are there other UI Text solutions?
TextMeshPro has a non-ui component that you could/should use
you could also put the UI version on a world space canvas
where can I find the non-ui tmp?
GameObejct -> 3D -> TextMeshPro
ohh and this will work with 2D games aswell?
ah alright, thanks for clearing two questions at once!
one simple option is to give the SO an enum then link it to a behavior with delegates. Random example from a tower defense game:
public delegate Target TargetChooser(Tower source, List<Target> targets);
public TargettingType {
Nearest,
LowestHealth
}
static Dictionary<TargettingType, TargetChooser> behaviorDict = new () {
{ TargettingType.Nearest, TargetNearest },
{ TargettingType.LowestHealth, TargetLowestHealth }
};
static Target TargetNearest(Tower source, List<Target> targets) {
return target.Min(t => Vector3.Distance(source.position, t.position));
}
static Target TargetLowestHealth(Tower source, List<Target> targets) {
return target.Min(t.Health);
}```
Then when you're actually dealing with your MonoBehaviour code you can do something like:
public class Tower : MonoBehaviour {
MyTowerSO towerSpec;
public void ChooseTarget(List<Target> possibleTargets) {
TargetChooser chooser = behaviorDict[towerSpec.TargettingType];
chooser(this, possibleTargets);
}
}```
this is all.. semi - pseudocode of course
but the result is in the SO you just get a dropdown for the enum to choose the behavior type, and it gets linked up this way in code.
What I like to do is use [SerializeReference] for those things
public class IChooser {
public virtual void Choose(...);
}
public class Nearest {
[SerializedFiled] private XXX xxx;
public override void Choose(...) { ... }
}
public class LowestHealth {
public override void Choose(...) { ... }
}
public class Tower : MonoBehaviour {
[SerializedReference] private IChooser chooser;
}
yep
ahh i have a better way to explain what don't work, when i get the height for example of this canvas, it gives something that i have to divide by the scaleFactor, but i can't get the scale Factor
there is inbuilt priority queue in csharp but i do i use it ?
i cant seem to use it
How would does one go about turning a spline into another object's x-axis so they can move along said spline?
Guess it doesn't have to be any axis in particular, just so long as I can reliably make it so traveling left and right along it works. X just happened to be the one I saw someone reference
experimental is disabled, and I tried to add it from the package manager.
If your using the Splines asset package, you could use EvaluatePosition (https://docs.unity3d.com/Packages/com.unity.splines@1.0/api/UnityEngine.Splines.SplineUtility.html#UnityEngine_Splines_SplineUtility_EvaluatePosition__1___0_System_Single_) then pass in t, being a clamped float between 0 and 1, that basically determines its percentage along the spline (so 0.5f would be 50% along the spline) - the function returns a float3, so youd then have to convert that set of numbers into a new Vector3 then do whatever youd like with it, this is largely how I handle it for a game where movement is restricted to a spline, since after you convert it to a Vector3, in world position you can chose which axis of that vector you want to "restrict to the spine" to still allow things like jumping/falling
nvm i was using the wrong parameter
So I'm still fairly new to splines and this method of coding so please forgive me if I'm asking a lot, but I'm kind of struggling to figure out how to actually get this to work. I assume I can't be referencing my main spline via a SplineContainer, but I really don't know how it wants me to reference it or how the code in the repository is actually meant to be integrated. I think I understand how to convert a float3 to a Vector3 at the least, but the rest is giving me trouble.
Do you know of anything that I might possibly be able to reference for a more concrete idea of what I'm supposed to be doing?
Sadly I dont, aside from some of my code and the docs, tbf though I havnt poked at this code in a little bit - the SplineContainer should be a part of your scene though, so you should actually be able to reference it as UnityEngine.Splines.SplineContainer, you could do a FindObjectOfType if you only have 1 in the scene, or directly reference it in a serialized/public variable, for example, I have a function that looks something like this:
public class Example : Mono
{
UnityEngine.Splines.SplineContainer c;
float t;
void Start() {c = FindObjectOfType<...>();}
public void Move(float direction) //-1f for left, 1f for right, 0 to stand still
{
t += Time.deltaTime * (moveSpeed * direction);
t = Mathf.Clamp(t, 0f, 1f);
var f3 = c.EvaluatePosition(t);
transform.position = ConvertF3ToV3(f3);
}
}
From input, or AI or whatever, I could call Example.Move(-1f) to begin moving left along the spline at some defined moveSpeed
I see. I'll try running with this then and hopefully I can get something rolling later tomorrow since I'm about to sleep. I've been trying to figure this out for a few days now and even my friends who have done coding for actual AAA game projects were losing their minds trying to help me so I greatly appreciate this! It's the closest I've been to a step in the right direction for a while. π
Np, im not too familiar with the Spline package myself, as its a recent requirement for one project, and havnt yet figured out how to properly take world positions and convert them to the spline for spawning, but actually moving along any random point, seems easier to do apparently lol, lemme know how things go
I will!
!collab
We do not accept job or collab posts on discord.
Please use the forums:
β’ Commercial Job Seeking
β’ Commercial Job Offering
β’ Non Commercial Collaboration
ok
in unity2d I have a bullet collision that spawns a particle system. The problem is that it spawns the particles in the middle of the collider because the bullet is traveling to fast. Does anyone know how to spawn the particles on the edge maybe by getting the colliders bounds and spawning it on the edge opposite of the transform.right?
if your bullet is moving fast enough, i would just raycast instead and add in some visual to act like a bullet has travelled this path.
but if you need the actual travelling bullet, maybe you could try using the contact points of the collision. Not entirely sure if that will produce a different result
its not fast enough to be a Raycast. But it is just fast enough where it will spawn a little to deep in the collider I did try to make it the contact point but that had the same result thats why i was trying to think of a way to do it with the collider bounds
use https://docs.unity3d.com/ScriptReference/Physics.Linecast.html between the bullets previous position and itβs current position. Then spawn the particle when the linecast hits something
ohhh this looks like it might work I'm gonna go give it a try thanks π
you'll likely need the 2d one
https://docs.unity3d.com/ScriptReference/Physics2D.Linecast.html
yeah definetly im just hooking it all up right now
How can I start a python script in a coroutine and wait for it to finish before proceeding?
have my doubts you can do that
In C# you can start processes and run shell commands though right?
So I could just do that and somehow wait until it finishes
you can try ig
Sounds like possibly
yield return new WaitUntil( () => process.HasExited );
I havent specifically ran python scripts in unity, but yes u can run it through c#
Also TIL this is a thing, for some reason π€ https://docs.unity3d.com/Packages/com.unity.scripting.python@7.0/api/UnityEditor.Scripting.Python.PythonRunner.html
yea that one Editor only
ahhh that makes much more sense π
for some reason it just skips past this
Here's my code:
public static IEnumerator CreateScript()
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "/usr/bin/python3.10";
psi.UseShellExecute = true;
psi.Arguments = "/media/guiguig/usb-drive/family-guy-ai-pre-main/make_script.py";
Process process = Process.Start(psi);
yield return new WaitUntil(()=>process.HasExited);
string output = process.StandardOutput.ReadToEnd();
UnityEngine.Debug.Log(output);
}
So i have a system to spawn stuff on a grid. But i don't want to have two things on top of each other. So i added colliders to these object. The problem is that I also made it that they keep getting spawned if you keep left click pressed. Meaning that 10 spawn before the collider can detect that. What should I do ? change aproach or reduce the speed you can place these objects ?
Just keep track of which objects are in which grid spaces. No need for colliders
what data structuer should i use for that ?
Either a 2d array or a dictionary
Huh
I will think about it, I am mainly a bit lazy to implement it
If your data is dense, use an array
If it's sparse use a Dictionary
They are extremely efficient
thanks for the help
What about list?
So turns out the issue is that i'm just completely unable to start any process
Anybody know how I can make a farming system for a top-down game?
What have you tried so far? Maybe Google if you haven't really thought of anything yet.
I tried google, all the systems i have found require a sprite and i cant use one (im not using a sprite)
Why would you use a list
The point is a collection you can address with x,y coordinates
How does a list satisfy that
"farming system" is extremely vague
Sounds like you've got specific constraints. You'll not be able to integrate the solutions they've design directly but should be able to incorporate some of the ideas.
what aspects of a farming system (planting, harvasting, watering, etc.) would i need to make?
No clue. Possibly everything that you're wanting/needing.
planting, harvasting, watering, etc.
i just dont know how to implement it
statemachine π
well yeah
You haven't shared why you can't use sprites?
Player sprites, i can use sprites anywhere else x. Thats just the game, you move with a "cursor" not a charactor rendered
Okay... I don't get it
You don't have a sprite acting as a player just a top down system with a cursor that moves you around
So take what you've seen from the tutorials and incorporate it not with sprite collision interactions but mouse pointer interactions.
okay sorry
anyway I can get visual studio to stop spamming (gives me this warning for every assembly) this warning, and rather hide it? (also the file definitely exists in that location)
Anyone know how to deal with NREs being fired from TMP when trying to use custom Sprite Assets?
I feel like I've done the normal steps, but nothing wants to render
Ah, unity restart fixed it
of course
Do child classes apply the changes by the property drawer on the parent class's fields? 
I feel like the way I worded it is crap. 
@loud wharf not entirely sure what you're asking here, but the default inspector will add any child fields under the parent class field. Property drawers are applied to fields, so if they're applied to a parent class field they will affect that field?
Need some help with the netcode, I wonder if that's the right channel
Okay so I tried this line and it still doesn't run my script, any suggestions?
Process.Start("/usr/bin/python3.10", "/media/guiguig/usb-drive/family-guy-ai-pre-main/make_script.py");
It doesn't give me any errors, but it also doesn't start the script. I even looked in system monitor and it never starts python.
From #πβfind-a-channel you would find out theres #archived-networking too
thanks
not trying to get you to show anything, just provide more context
I guess to provide it as an example.
PropertyDrawer targets Foo.
Then there's Bar which is inheriting from Foo.
The question is if the Foo's field inherited by Bar is still affected by the property drawer.
yes
kay
When I was searching, I saw examples having to make property drawers for each inheritor and I only need to customise the base one so I was thinking if that's necessary.
I believe those would be referring to if you had a field Foo and a child class Bar
a custompropertydrawer attribute only applies to the direct class by default
you can use the useForChildren attribute to make it apply to child classes tho
π
for reasons that are stupid I have a button that i need to invoke via code but should never be able to be pushed by the user
should i just turn off the image and make it 1 x 1 pixel
You could position it outside of the canvas? eg. (-1000, -1000)
oooh cheers
just curious, why does this have to be a button? why not just c# events or unity events on an empty gameobject?
I was unable to figure that out
you should really look at a unity event at least, you can set it up similarly to button events when its public or [SerializeField]
you could get away with hiding the button, but eventually you'll have 100 buttons hiding around your canvas
I only need the 1 haha
can I call methods of an associated script from a statemachine behaviour? do I need anything in the behavior script?
I would like to design data structures in a voxel based city building game. They are scriptable objects.
There are two different data structures. One of them is ElementDefinition. Elements are independent of views (voxels, prefabs, sprites, etc.). They are pure data like seed, gold, water, plant, etc.
The other is WorldObjectDefinition with two children, VoxelDefinition and ModuleDefinition.
VoxelDefinition contains 6 textures for each face, ElementDefinition with its amount and other stuff.
For example a rock voxel has 6 rock textures for each face and 10 kg stone element.
ModuleDefinition contains a prefab. All world objects rendered as prefab, inherit from ModuleDefinition like BuildingDefinition, PlantObjectDefinition, etc. These data structures can be composed of ElementDefinition with amount, As an instance, PlantObjectDefinition has PlantDefinition.
It is worth noting some objects like rock, can be as voxel or prefab.
Is it OK? Can you suggest your way to handle it?
Hi guys, can someone tell me how to add a delay before the start of one video and if can I add in the same video player more than 1 video?
Neither of these.
Don't use inheritance to solve the problem better solved by composition
Use Timeline
is there any particular reason to not use AssetDatabase.LoadAssetAtPath() during runtime?
I have a scriptable object I want other scriptable objects to be able to reference after being created at runtime, the alternative would be a singleton but that is more limiting by virtue of there only being one
Context is I want to have a dictionary of gameobjects for an in-game level editor
The AssetDatabase api is not available at runtime
Use IDs
Like other said, it is not available at runtime. Instead, you should use AssetBundle or Resource Folder. The former being the best option while the later can work for prototype project.
Alternatively, you can force a reference to the asset you want in the scene and it will be loaded with the scene.
ok thanks for the help :)
does anyone know why caretPosition of TMP_InputField is not changed immediately?
private void Update()
{
typingField.caretPosition = caretPos;
if (Input.GetKeyDown(KeyCode.Backspace) && caretPos != 0)
{
caretPos -= 1;
typingField.caretPosition = caretPos;
typingText[caretPos].ChangeColor(defaultColor);
ChangeText();
}
}
You can code of TMP_InputField. Seem like you might want to use stringPosition instead.
private void OnFillVBO(Mesh vbo)
{
using (var helper = new VertexHelper())
{
if (!isFocused && !m_SelectionStillActive)
{
helper.FillMesh(vbo);
return;
}
if (m_IsStringPositionDirty)
{
stringPositionInternal = GetStringIndexFromCaretPosition(m_CaretPosition);
stringSelectPositionInternal = GetStringIndexFromCaretPosition(m_CaretSelectPosition);
m_IsStringPositionDirty = false;
}
if (m_IsCaretPositionDirty)
{
caretPositionInternal = GetCaretPositionFromStringIndex(stringPositionInternal);
caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
m_IsCaretPositionDirty = false;
}
if (!hasSelection)
{
GenerateCaret(helper, Vector2.zero);
SendOnEndTextSelection();
}
else
{
GenerateHightlight(helper, Vector2.zero);
SendOnTextSelection();
}
helper.FillMesh(vbo);
}
}
Why are you manipulating the caret for delete ?
It is already managed by the component.
that's because...
yes, I have changed built-in code
If you gonna change the code, you must be able to solve those issue O.o
Also, why are you not using 2 text instead ?
Render one on top of the other.
what do you mean?
I mean exactly that.
I do not know why caretPosition is changed like that
This is because you are not correctly using the API.
If you gonna change things in Built-in, you MUST be able to solve things like that.
Instead of changing how the InputField works, make one text gray (Non InputField) and the other white (InputField)
I do not know what you mean and I also wonder if smth that I do could be implemented like this. I am changing the color of the characters in the text and moving caretPosition when typing
A way easier way would be to make 1 background text and other front text
Try to use MarkGeometryAsDirty after setting the carret.
I don't think so, you still need to divide characters to change their alpha
private ColorfulChar[] typingText;
private void ChangeText() => typingField.text = string.Concat(typingText.Select(w => w.parsed));
What?!
I do not agree.
It is just one level Inheritance.
When it is said composition over Inheritance it does not mean don't inherit! It means don't add another level of inheritance every time you define some new classes
It also does not mean that. It is kinda complex, but I see it as a way to solve/prevent the Diamond Problem. Normaly, you use interface for that, but if you do that you need to rewrite every implementation.
https://en.wikipedia.org/wiki/Composition_over_inheritance
https://en.wikipedia.org/wiki/Multiple_inheritance
In other words, in your situation, it seem more than adequate to use inheritance as an object of a given type is definitively a "Definition". That being said, as your code progress, you will need to complement those child definition with composition instead of increasing the number of functionnality in your "Definition".
Ok, was worried that it's not an attribute, but found out it's just another overload for CustomPropertyDrawer. 
Ok
You still could change the color of the back font to 0 alpha if alpha is an issue.
This way, you will not need to change any code from the TMP_InputField
then how do I disable Delete?
You replacing the behaviour of delete with changing the color
I do not see any way to implement it
That it is what you are trying to do
Vector2Int one = new(cell.pos.x+1, cell.pos.y);
Vector2Int two = new(cell.pos.x, cell.pos.y+1);
Vector2Int three = new(cell.pos.x, cell.pos.y-1);
Vector2Int four = new(cell.pos.x-1, cell.pos.y);
search.Add(one);
search.Add(two);
search.Add(three);
search.Add(four);```
there must be a less boilerplate way to do this right...
I am saying that you do not need to remove the delete key, but can instead have 2 text (One that you modify while the other you do not)
List<Vector2Int> search = new() {new(cell.pos.x+1, cell.pos.y), new(cell.pos.x, cell.pos.y+1), new(cell.pos.x, cell.pos.y-1), new(cell.pos.x-1, cell.pos.y)};
the Delete key will modify one text so that they will be then different
look like you are doing some dfs in orthogonal direction @mossy minnow
ye
I think you mean that you want to keep the backspace but not the delete ?
You can removing only the delete ?
And keep the back space ?
And remove the possibility to change the focus to other than the last key ?
yes, I am trying to implement the basic typing system from this site: https://monkeytype.com/
yes, Delete should do nothing
im trying to search the cells that are directly u/d/l/r of the current cell, and if a specific var inside that isnt null, add to a List
Anyway, if you gonna change the TMP_InputField, you gonna try to be a bit more autonomous as most people has not done that. Read the code, and analyze it. There is multiple function that could be responsable to redraw the cavet.
I named two of them.
ok, thanks for your help π€
int2 is similar to vector2int but burst compatible, you can check it to vector2int
MarkGeometryAsDirty - stringPosition
what do you mean by "stringPosition"?
it should be parentY+DirXXX.y .....mistype
In the TMP_InputField code
I do not know, this is only guess from reading the code
It might work, or it might not work.
i will try π€
Also, you can try to do a double for loop if it is only for iterating.
for(int x = cell.pos.x - 1; x <= cell.pos.x + 1; x++)
for(int y = cell.pos.y - 1; y <= cell.pos.y + 1; y++)
this loop through diagonal and orthogonal direction
Oh yeah, my bad, this way both diagonal that we needed
hey guys, how to use a script as a return of a function? is something like the following possible?
public static class HeroDictionary
{
private static Dictionary<string, Unit_Combat> nameToScript = new Dictionary<string, Unit_Combat>()
{
{ "FeuerStarter", new Fire_Unit_Combat() },
{ "WasserStarter", new Shield_Unit_Combat() },
{ "PflanzenStarter", new Heal_Unit_Combat() }
};
public static Unit_Combat GetCombatScript(string heroName)
{
if (nameToScript.ContainsKey(heroName))
return nameToScript[heroName];
else
return new Dummy_Unit_Combat();
}
}
i then want to call the function
unitScript = HeroDictionary.GetCombatScript("someNameInDict");
for(int i = - 1; i <= 1; i++)
Vector2Int a = new Vector2Int(cell.pos.x + i, cell.pos.y + i)
Vector2Int b = new Vector2Int(cell.pos.x - i, cell.pos.y + i)
Hello, just wondering is it fine to have constraint as Component or should I do MonoBehavior if I'm only using functions from Component? What are your preferences? π€
Ask yourself what inherit from Component
Is it something that you support
well its MonoBehavior but my brother strongly suggested to use MonoBehavior instead of Component which I don't understand why so asking some preferences here
From his point of view, it might be because what you truly are supporting is MonoBehaviour, not component.
What does "support" mean here tho?
What you are expecting to have
well.. anything that can sit on a gameobject I suppose.. though I clearly don't understand
tbh Component or Monobehaviour make no sense in this scenario
On the timeline can I use triggers to start the animation, right?
So, in that case component is the correct answer. Same if you will never see a Component ever, but always MonoBehaviour.
How can I get the screen position of an object? I'm using Vector2 player = GetComponent<Camera>().WorldToScreenPoint(transform.position); to get it but it tells me that there is no "Camera" attached to the game object, even though I have it as a child and one component that shows blue because its inside the 2d plane
In more theorical term this is the application of Interface Segregation Principle.
Ok, pretty dank. I don't understand enough
What does the 2nd sentence mean?
I'm confused for no reason lol
Nothing can inherit from Component as far as know. That make sense
Hmm
Won't just having MonoBehaviour or Component in my case work the same except that I don't really use anything from MonoBehavior?
Yes, it will work. It is only a theorical thing.
You should use what you truly need
Which is component
However, you can also say, that a Component alone does not make sense
We always use Monobehaviour
So, in this sense, you should use MonoBehaviour to constraint the amount of concept needed to express your class.
Both are valid argument
There is one argument brother is throwing at me that a class:
public class Test : Singleton<Test>
{
public void Display()
{
print("yo");
}
private void Start()
{
}
}
should not be able to use MonoBehavior messages like Start() as you are constrainting T as component in Singleton script and according to readability, it just tells that T is only a component and it should not have MonoBehavior functions but it does.
So, in your case, MonoBehaviour make more sense.
because Singleton<T> inherits from Monobehaviour which is why your constraints make no sense
Because you NEED the behaviour of a MonoBehaviour.
That kinda makes Constrainting Component ever as useless tho.
In this situation
It won't work without it tho
If you do an extension method for a GetComponent, you should use a constraint on Component.
public static bool TryGetComponentInChildren<T>(this GameObject go, out T component) where T : Component
{
component = go.GetComponentInChildren<T>();
return component != null;
}
So what do you think about it? My brother says because we are using MonoBehavior functions in the inherited class, T should be constrained as MonoBehavior and not Component even if the Singleton class itself will not need anything in MonoBehavior
As you said, it requires to be a MonoBehaviour. The alternative is not practical.
Even if I use Component as constraint in the Singleton class, it still works absolutely fine.
My brother just hates because it takes away the meaning in readability context.
unity messages like Start and Update don't really care about C# semantics
they use reflection to find the methods
so it matters not
I mean, it does not. It make more sense from my persepective. I though you said it did not work.
Anyway, I already answer the question
Both argument are valid.
Ok thx. My brother still want answer to one question that what do you think about in readability context
Like does it matter if it's constrained as Component or not.
Like I said, this is a valid argument. It is more readable because there is less "Unknow" concept such as what is a component.
However, if you want to follow the SOLID principle, you should restraint to the smallest interface.
Aight, screw it, i goddamn hate property drawer.
It's a trap, just focus on developing your game ;)
Lol my brother still hates it in readability context while taking both inherited and singleton class into account.
Can't deal with it. Arguing from 2 hours.
Yep. dies
ah yes this infamous problem
try using [NonReorderable] attribute
I'll continue this tomorrow.
Won't that make the list not reorder-able? 
remove it when you wanna shuffle things around
That sure sounds convenient.
Is there any way to fix this? 
Actually nvm, I'll just deal with this tomorrow.
Since I can't show code and stuff ATM.
Hello. I can't get any 'Input' events when I'm inside 'GUI.TextField', halp :(
why are you using GUI.TextField exactly ?
For fun. Though it' would be nice to create UI through code, easy to transfer to another project without using any prefab.
OnGui should be only used for testing
prefabs are very easy to transfer over, you can literally copy and paste it. It's an asset
Kind of trying to use it exactly for testing purposes :D. Making a cheat console
ok and it's limited so no such thing as "input events"
But I can't even hit Enter at the end of my command, because it just eating all the input. Google didnt help
do the sensible thing and use TextMeshPro
yeah, I don't need it to handle my events, I just want it to stop eating them >:(
learn how to use a string input then idk what to tell ya
using an outdated UI system, not sure that makes anything cool but you do you
I don't get what your question is about anyway you arent clear
I just checked my cheat console code, looks like I ended up using TMPro for the text field because of similiar issues
a proper console needs a scroll rect imo
I create field
input = GUI.TextField(new Rect(8, 8, Screen.width - 8, 20), input);
And when my game is focused on it, I can no longer recive any input events
print(Input.GetAxis("Submit")); // Not working :(
No such issues with tmp
So yeah, I guess if there is such a insane limits, there is no other way
whatissues are you talking about ? I don't even see proper usage of input
I just see 2 diff strings
It looks like it can work with new Input system from one of the video I watched, but I can't use it on my current work project sadly.
ok ? not sure how this satement helps anything..
It's just a debug, to see if Input value changes.
if (Input.GetAxis("Submit") == 1)
{
// Do stuff
}
what does this have to do with TextField Inputs? also this def belongs in #π»βcode-beginner
A bit offensive :D
Does anyone have some resources i can take a look at about using root motion with netcode for game objects? I've been having problems about clients character being completely still, while the host character is seen by the clients as very jittery, almost as if its string to do the animation but going back to the default pose and i'm pretty stumped about it 
maybe this is more of a networking question 
there shouldn't be anything particularly special about doing root motion -- that's just the animator moving based on the animation
I don't think I ever tried doing root motion with NGO tho
i can't really pinpoint what's giving me this problem then
my characters have the network animator component too
public class popupShop : MonoBehaviour
{
private VisualElement root;
// Start is called before the first frame update
void Start()
{
GetVEElements();
HideRoot();
}
void GetVEElements()
{
root = GetComponent<UIDocument>().rootVisualElement;
}
private void OnCollisionEnter2D(Collision2D collision)
{
ShowRoot();
}
private void OnCollisionExit2D(Collision2D collision)
{
HideRoot();
}
void ShowRoot()
{
root.style.display = DisplayStyle.Flex;
root.pickingMode = PickingMode.Position;
}
void HideRoot()
{
root.style.display = DisplayStyle.None;
root.pickingMode = PickingMode.Ignore;
}
}```
So when my player collides with the side it works OnCollisionEnter2D
but when i hit from bottom it doesn't work
(it works if I make it all triggers)
hey guys, i am looking to integrate nvidia highlights / ansel / etc... into my newest game. the former plugins / sdks for that are now deprecated / legacy things though. since these features still very much exist, there must be another way to integrate them now, but after searching a long time all i could find was a 4 year old forum post vaguely discussing this and nothing else. unfortunately following their steps just led to a dead end for me.
does anyone here know the new way to integrate these functionalities nowadays? (even unmanaged code interop is fine)
is there a easy way to do water in unity?
Slap a transparent material on a plane mesh
you asked for "easy", not "high fidelity"
I think there's an experimental physics driven water in HDRP.
Other then that, asset store or write your own shader.
Open your favorite text editor and write it like any other code.
Or you can use the Shader graph to make it simpler
ah
Ill look into it
how do I open/use the shader graph
ah ill just read the docs nvm
water physics would be nice but I also think they would destroy my computer
fake it 'til you make it!
yeah
is there a way to make a mesh like
jiggle
like water might
Because water usually doesn't sit still like a cube
can I edit the vertices?
why code generated voxel looking weird?
void renderCube()
{
VoxelInfo VoxelInfo = new VoxelInfo();
List<int> triangles = new List<int>();
triangles.AddRange(VoxelInfo.upTriangles);
triangles.AddRange(VoxelInfo.bottomTriangles);
triangles.AddRange(VoxelInfo.leftTriangles);
triangles.AddRange(VoxelInfo.rightTriangles);
triangles.AddRange(VoxelInfo.forwardTriangles);
triangles.AddRange(VoxelInfo.backwardTriangles);
triangles.Reverse();
Mesh mesh = new Mesh();
mesh.vertices = new VoxelInfo().vertices;
mesh.triangles = triangles.ToArray();
meshFilter.mesh = mesh;
}
```
Your cube corners probably share vertices, making the corners have one normal averaged between the vertices.
woah is that a custom renderer thingy?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChunkInfo
{
public Vector3[] vertices = new Vector3[8] {
new Vector3(0, 0, 0),
new Vector3(1, 0, 0),
new Vector3(1, 0, 1),
new Vector3(0, 0, 1),
new Vector3(0, 1, 0),
new Vector3(1, 1, 0),
new Vector3(1, 1, 1),
new Vector3(0, 1, 1)
};
public List<int> upTriangles = new List<int>() {
4, 5, 6, 6, 7, 4
};
public List<int> bottomTriangles = new List<int>() {
0, 3, 2, 2, 1, 0
};
public List<int> leftTriangles = new List<int>() {
0, 4, 7, 7, 3, 0
};
public List<int> rightTriangles = new List<int>() {
1, 2, 6, 6, 5, 1
};
public List<int> forwardTriangles = new List<int>() {
0, 1, 5, 5, 4, 0
};
public List<int> backwardTriangles = new List<int>() {
3, 7, 6, 6, 2, 3
};
}
Should I do different vertexes?
You should have 3 to 6 separate vertices per cube corner.
Yes, you need to give each quad its own vertices.
Ah, maybe just 3π
it'd be 6 for the corners where 6 triangles meet
well, I guess you could get away with just 3
since the two tris that make up a face can share vertices
If you've ever displaced a mesh with sharp shading, you probably noticed that the faces aren't actually connected
i got it thanks you save me a lot of time
π
i can fix this
making minecraft like chunks dont seem to hard
because i make a voxel π
how can i make different materials for triangles
Submeshes probably.
But It that kind beats the purpose of using one mesh.
You should have one material that can render differently based on some data.
I almost rendered the whole chunk as a single mesh
I guess I should submesh each chunk
And you probably want to keep it at that.
how can i make basic cubic uv for this meshes?
What is basic cubic uv? It depends on how you want it to unwrap.
Something like this.
Just map it to the correct vertices
Woops, it should be 0,1 at the top left π
i got it
Basically you want to map 6 squares to a texture (which is also a square) thatβs done most optimally by having the squares arranged in a 2x3 grid in the texture.
xd
But if youβre mimicking minecraft then you probably want a more atlas based approach
like this?
Yes
Rider
i use vs code on window and there is linux version of vs code
I need student account for this
Or money
Rider is not free but it's by far the best IDE for C# on Linux
if you don't want to spend money - VSCode for you.
I want the spend money but i dont have money becouse my country's have a political economy crisis problem π
this is bad
If you're a student by any chance, JetBrains has free educational licenses
i will research then
thanks
Oh wait I think vertx was telling me their early access program is also free! https://www.jetbrains.com/rider/nextversion/
This is unlimited to use?
From a very cursory googling, it sounds like there are no restrictions on it, yeah. You might have to deal with somewhat more bugs than their stable product however
thats a not a problem for no money programmers like me
EAP builds are valid for 30 days after release. If you're lucky, a new build will be released before then, which resets the duration. But there are often gaps longer than that where they haven't released a new EAP build.
@gusty viper Don't post off-topic. Read #πβcode-of-conduct
yes hello hi i have the question of all time
what's the best way to learn C++
i would like to code in unity for a game, but i do not know how to code in c++
Unity doesn't use c++
look up how
unity use c#...
Unity uses C#
Can you link the google link where it said C++?
unity
There are tutorials pinned to this channel, and you can also do the !learn series.
π§βπ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
!learn
π§βπ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
i have this, despite it being bing
i just saw unity and c++ in the same screen and went "ooo im gonna go learn that"
my brain is quite small, i apologise for this
Unity is written in C++ and C#
but you code just on C#
this is word salad made by an AI
god I love the future it's SO GOOD
i dont like salads so i will stop looking at this
use google πͺ
thanks idbb from the official unity discord server
can I ask what is the code for start an animation on the start of the current scene?
two separate problems
one: run something when the scene starts
two: play an animation
for the first, you can just wait for Start to be called on something that's in the scene
The unity profiler is creating a lot of noise by, from what I can see, profiling itself profiling. It makes it a bit difficult for me to see if anything is actually going on. Can I prevent this in any way?
show an example.
There is also UnityEngine.SceneManagement.SceneManager.sceneLoaded, an event that fires when a scene is loaded
probably not as straightforward as this, though
you're profiling the editor here
are you trying to profile the editor?
or are you trying to profile the game?
If I switch to play mode I get what appears to be the same spikes
yes, the editor will occasionally spike
just, I can no longer see that it is the profiler
So if the editor loop is 90% of my ms, that means I'm probably fine?
and I should focus on whatever happens in the PlayerLoop, if the percentage goes up?
Turning off the "Others" category will hide it
Yes, that's going to be what's relevant for you
Cool. so if normal gameplay looks like this, with "Others turned off" then I'm probably doing fine
right?
that's running pretty fast, yes
Well it's just a basic level so hopefully I would still have some headroom to work with. Thanks for the help
Hey, this code should Debug.Log the name of the sprite touched with the mouse but it don t always work... has someone an idea?
if (EventSystem.current.IsPointerOverGameObject())
{
PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
pointerEventData.position = Input.mousePosition;
List<RaycastResult> raycastResults = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerEventData, raycastResults);
if (raycastResults.Count > 0)
{
GameObject touchedObject = raycastResults[0].gameObject;
Debug.Log("Objet touchΓ© : " + touchedObject.name);
}
}
in what way does not work? does it not log anything at all? does it produce an error? does it log the wrong thing?
it work 1/2 of the time when i click on a sprite
Follow up question, I'm getting a fair amount of time spent in the "RenderPipeline.InternalRender" function, but it appears most of it is spent in the ProfilingScope constructor and the ProfilingSampler.Get(). This is still just the profiler creating noise, right?
And, what is an acceptable amount of garbage collection allocation to do per frame?
0 allocations per frame is ideal
don't worry about your non-code profiling samples unless you're profiling an actual build. It's always going to be noisy and somewhat inaccurate in the editor
I think I am missing something.
When typingText is List, the color of the chars is not changed, but when Array - everything works perfectly
private ColorfulChar[] typingText; // works
private List<ColorfulChar> typingText; // nope
// Start()
typingField.onValidateInput += ValidateInput;
private char ValidateInput(string text, int index, char c)
{
string binary = Convert.ToString(c, 2);
if (binary == "1001" || binary == "1010") return '\0';
if (c == typingText[caretPos].c)
{
print("YES");
typingText[caretPos].ChangeColor(correctColor, CharCheck.Correct);
}
else
{
print("NO");
if (typingText[caretPos].c != ' ')
typingText[caretPos].ChangeColor(wrongColor, CharCheck.Wrong);
}
// print(binary);
ChangeText();
caretPos += 1;
return '\0';
}
is colorfulchar struct?
yes
the indexer of list return the struct and you call a method on the returned struct only
the struct in list will not be changed
any ideas to do it with list?
or any other enumerable that size can be changed
i use unsafeList and use .Ptr to deal with this problem ie (list.Ptr+index)->method (or (list.Ptr)[index].method)
what i know: dont use the indexer if possible
You could maybe like
var ch = typingText[caretPos];
ch.ChangeColor(correctColor, CharCheck.Correct);
typingText[caretPo] = ch;
...but admittedly that's probably not ideal. Or use a class instead of a struct
Vector2 spawnPosition = playerData.rigidBody2D.position;
float randomX = Random.Range(0f, 1f);
float randomDirX = Random.Range(0, 2) * 2 - 1;
float randomY = Random.Range(0f, 1f);
float randomDirY = Random.Range(0, 2) * 2 - 1;
spawnPosition .x += randomX * randomDirX;
spawnPosition .y += randomY * randomDirY;
I am trying to figure out how to spawn enemies around the player, but outside of the camera view.
I tried adding +3f to x/y but the effect is not what I'd expect and enemies start spawning in the corners(outside the view, but only corners)
Probably because I am removing the ability of them spawning on x 0 or y 0 by adding + 3f to the result.
In the above example enemies spawn directly next to the player between 0 to 1f distance.
That is perfect, what I want is for them to spawn further away(but in same general direction)
yes, I think I might use it
I am thinking of adding 2d rectangle around the camera that will act as a spawner.
Sounds interesting, I create a mask around an area to spawn them in
rather, make an area around the player visible, but still extend the camera view past that and spawn monsters while hiding them
That sounds confusing
What does that achieve compared to setting up ~4 rectangles around the camera and spawn enemies at random points inside those rectangles?
Tbh with that said...I might just get camera viewport width/height and calculate the "rectangle" in code so I don't even need to add them in the editor.
Tho that still won't be perfect, it has to be more like a circle so enemies spawn all around at about the same rate.
@upper pilot so I think you should consider using https://docs.unity3d.com/ScriptReference/GeometryUtility.TestPlanesAABB.html
"check if GameObject is visible to the camera"
Huh apparently its "frustum" but unity calls it "frustrum"?
it does not matter, you should try to read that documentation
private void IsVisibleToCamera()
{
Plane[] frustumPlanes = GeometryUtility.CalculateFrustumPlanes(Camera.main);
return GeometryUtility.TestPlanesAABB(frustumPlanes, objectRenderer.bounds);
}
smth like this
I don't know if it's worth adding more complexity to the simple problem.
I don't use planes
yes, you have said:
I am trying to figure out how to spawn enemies around the player, but outside of the camera view.
"outside of the camea view"
its frustum, i think that one might be a typo..
Right, I should mention that I want them to spawn around the player at certain distance.
I said outside the camera, because that's the goal, but I can just add a number that will work.(Well I can't, cuz adding a number doesn't solve it, but that's the goal :D)
where?
You can use this function with CalculateFrustrumPlanes
on this page
yes, that's easy, the problem is "outside the camera"
I'd like to convert this code and add distance away of the player.
If that makes sense.
what about camera?
I really don't want to go into rabbit hole of planes and frustums
Since I never worked with those things.
Ignore the camera π
its really not a rabbithole.. this is like 2 lines of code to check if something is within the camera bounds
I just said it, cuz its kinda relevant but if I can spawn enemy 500px around the player then its good as well.
so you do just make while loop and wait until Vector is outside the Camera view
"px"?
(instead of px its like 5f on each axis around the player in my case)
you are going to make this harder on yourself if you need it not visible on spawn, a frustum isnt as scary as it seems
it is quite literally just a shape
But how does that let me spawn an enemy outside the bounds?
Won't it just let me detect if the enemy is within camera view so I can look for another spot?
so you need to spawn at x [-5f -- 5f] and z [-5f -- 5f] as I have understood
shape like these, where the pink plane is your "near plane" meaning how close i can see
orange is far plane, aka how far u can see
the other planes are just connecting the 2 as a pyramid
the camera would be pointing down in this case if it used this frustum
It's more compllicated than that I think.
It has to be more like a circle around the player.
then use trig to solve the angle of unit circle * 5
Because if you just do -5f to 5f then they will spawn in corners only.
yeah, they have already said that using they don't gonna use those complex things
That is the issue I am trying to solve π
Tbh I have an idea, since someone helped me earlier with angle to Vector conversion
I guess this is that you are looking for https://answers.unity.com/questions/714835/best-way-to-spawn-prefabs-in-a-circle.html
I might use that probably
float angle = 20f;
Vector2 direction = Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right;
this is just trig then if u wish to spawn it randomly around the player. Choose a random angle and calculate the cos, sin of that angle to get where that should be 5 units away
I dont know how to use cos/sin lol, but someone earlier mentioned that it's not necessary.
The code above gives me a vector based on an angle.
I can just multiply it by 5f
I think that might work.
I dont know much about quaternions unfortunately, so hopefully you know what that does
Same haha
yes, I have mentioned this before too, cause you have been describing another problem
i really would just use trig, the link IDBB sent u does the exact solution
Yes, just multiply these vectors by 5
you needed to "spawn bullets from the player" and I have suggested to you how to do it
Yes my savior is here π
1 line to solve 5 problems
Quaternion.AngleAxis takes degrees and an axis. It produces a rotation around that axis by that many degrees
Multiplying a Quaternion with a Vector3 produces a rotated vector
So, if you were to run that line many times with many different values for the angle, you'd get a bunch of points on a unit circle
Yep, I just dont know how to use cos/sin so I needed a simple and crude solution that just works.
Until I learn those things.
Multiply those vectors by a constant will produce a larger circle.
The methods provided in Vector3 and Quaternion can let you avoid doing much triginometry.
I find it to be much more reliable.
yes, I don't remember sending solution with cos/sin
i see, thanks for the explanation
since we're multiplying the quaternion with Vector3.right, you get a variety of vectors produced by spinning a right-vector around the Z-axis
i.e. a circle
yes, I don't remember sending solution with cos/sin
did u look at the link u sent
no, I do not mean that
they have asked the question in #π»βcode-beginner some time ago
ah
that would make more sense for 3D, btw
since it performs a rotation around the Y-axis
yes, it was just an example
I do not know the axis they should use
just guessing
tbh i thought this was 3d from the start
Do people use Vector2 in 3D games?
ScreenPosition ??
I usually specify Vector2 to be clear, but maybe I should add that it's 2D just to be clear π
I don't know.
ok
I don't have that much experience with 3D.
i sometimes use it for level generation
I am struggling with circles and angles atm
for things that are effectively 2D, like terrain
then I forget to convert from Vector2 to Vector3 properly -- (a,b) to (a, 0, b) -- and it breaks
circles the way to go
Makes sense, still a lot to learn <_<
cause then you get to do cool stuff like wave funcs with oscillations
I guess you could do some squiggly square spawn waves and stuff
circles just make more sense to me when keeping enemy spawns dynamic
yeeeah
they dont necessarily need to be off camera too like I was saying. Could just obscure them from view till they are close enough
Maybe I am confusing camera and view, but I meant for them to appear outside of player view.
I thought camera and viewport are the same size(by default)
Btw, is there a way to convert direction(Vector2) to angle? π
depends on what the angle should be measured with respect to
if you just want to go to back to the angle you would've punched into AngleAxis, I believe Atan2 is what you want
Thanks, I will try that
Actually maybe I am doing it wrong lol, but I just want to rotate an object in the direction its moving.
I assume there is some sort of Rotate function that takes vector2 as a parameter?
set transform.right to the movement vector
that will align the right side of the object with the vector
Like LookDirection();
or maybe transform.up
This maybe
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
Found this on a forum, guess atan2 is the way π
How does that compare to the above?
oh it's the angle?
so you don't need Mathf.Rad2Deg?
and atan2
But it doesnt rotate the object right?
I guess it should?
(But you'd probably want transform.right or transform.up in 2D as transform.forward is the direction of the object's local z axis)
nice
It's for the bullet in game so I am not to worried about breaking it as long as it flies towards correct direction π
this is #π»βcode-beginner material. i would suggest using !learn ; it's pretty fundamental
π§βπ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
ok
Hello everyone ποΈ I want to use Unity new Input system with Netcode, is it possible ?
yes
Could someone help me with this #π±οΈβinput-system message error?
Hello gentlemen, need some help with the following error
Why is this cast giving me an error? Very confused
seems like the object in the array is not a GunItem object so it can't just be cast to it like that and you haven't defined any conversion operators in either of those classes
Oh i wasnt aware you needed a conversion operation with casting to inherited classes
you're downcasting which requires the object either be the type you are casting to or have a conversion operator defining how that cast works
I am messing around in Unity, trying to optimize some runtime textures that are fetched from some server. I want to do the whole messing with the texture on a seperate thread so I am probably gonna need to mess with the raw data iirc. So I do need to know what format I am messing with. Does anyone know what this means? I know my IDE is able to fetch enum names, but like, it just responds with a number. Is it just saying D32_SFloat?
Does anyone have an example of how to return the current page and the parameters url of a webgl build. I can't get the parameters but I can get the url. I have been stuck on this all day.
var GetUrl = {
GetURLFromPage: function () {
var returnStr = "not found";
try{
returnStr = (window.location != window.parent.location)
? window.referrer : window.location.href;
} catch (error) {
console.error('Error while getting Url: '+ error);
}
var bufferSize = lengthBytesUTF8(returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
}
};
mergeInto(LibraryManager.library, GetUrl);
Would there be a way to approximate the volume of a room using bounding boxes?
Im sorry but do you know of any videos or refrences on how this works, only found an offical Unity video and it did not cover conversion operators when downcasting
it's literally nothing to do with unity. it's how C# casting works
I looked it up in general and that was just one of the top videos that came up
why are you even trying to cast an object that is not of type GunItem to the GunItem type?
I am attemping to have a base item class for runtime items, which stores normal item variable such as durability, and have specialized item classes for things like guns, which need magazine capacity stored
okay so you can store a GunItem object in the array of the item type, but you cannot just cast an item object to GunItem unless that object already is a GunItem type or you've defined a conversion operator for it
i have a question:
im working on an api and i wanna do it like this:
get data
clean it
store it in a database
get the info from the data base
present it in the form of an api key
present it the key on an interactive website
and boom
but im very new to data science but im pretty good at python
can anyone tell me how would i present the data in the data base and then in the form of a key
this doesn't sound unity related
yes ik but can anyone pleasee help me?
go ask in a discord server where the question is relevant. this server is for unity-related topics
actually, I am getting the location of the build but would like the page the build is embedded in
I don't think that's possible unless you have access to the JavaScript on the page
Pretty sure you ship JS with your Unity build to pretty much any place that would host a game. JS is used to load Unity and provide some additional functionality.
I mean communicate with it. Maybe you could with a lib but i don't know how exactly
HI everyone, i have the next code:
TextMeshProUGUI[] texto;
void OnTriggerStay2D(Collider2D other)
{
Collider2D[] contacts = Physics2D.OverlapCollider(GetComponent<Collider2D>(), new ContactFilter2D(), new Collider2D[10]);
int count = contacts.Length;
texto[0].text = count.ToString();
}
I get the error message saying "can't convert type 'int' in 'unityEngine.Collider2D[]'"
Why and how do I fix it?
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCollider.html
the method returns an int not an array. the last parameter of the method is where the array goes to be populated
you should also store the results array as a field so you aren't re-creating it every single time you call the method (not that you can even use it with your current setup)
How can I change this value through code. Its an editor background value so I need an editor script
I couldnt find anything specific on google
Any idea why onPointerUp is firing wrong in my ui?
https://paste.ofcode.org/Rz8PnW2ddiDMmQEFxnQaf
this is the code being used, the script is on a parent thats a few objects up the hierarchy
maybe explain a bit more why it's wrong
so all of those slots are basically the same, the ones on the left let you grab the circle and move it all over the UI, the ones on the right you can only move it within the slots square and if you go outside of it it fires onPointerUp and drops the circle again
the left only fires onPointerUp if you actually let go of the mouse button
I would try disabling extra objects around it and compare PointerEventData
oh that's pretty strange if they all derive from the same slot class
Also, there are events for dragging so you're not always checking when you click your mouse. Your method is probably fine though, just a suggestion.
the inventory slots are nested in the other objects on the right, disabling the other slots didn't change anything though
I actually was using that, I recently changed it in an attempt to fix the issue
this is the hierarchy if that helps, the drag and drop code is in UI, the slots that dont want to let go are in the scrollview
Well, could be a logic problem with the dragging and raycast, perhaps?
Also, you should consider looking more into the pointereventdata, there's a lot of extra work you're doing, which if you minimize could perhaps fix the problem.
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.PointerEventData.html
looking at the pointereventdata and the link it might be a conflict caused by the scroll view
Ah, should maybe throw some logging to see if onpointerup firing or your dragging bool is being set another way, because that's the only thing happening in your update otherwise.
yeah i have a breakpoint set on the first line of onPointerUp
For Entities package, how do you assert that an IComponentData struct requires another IComponentData class? I can't find an attribute
what do you mean by this? There is no [RequireComponent] like thing as you are in total control of the baking, do it via the Components that bake them. (also there is #1062393052863414313 for entities questions)
anyone unable to rename script with F2 in VS2022? Tried and it just went through with normal enter button.
Hey everyone Im making a clicker game similar to cookie clicker and Im having a problem with my leaderboard system. Currently Im using the lootloacker api to submit my scores online but this api only allows me to upload my score as an "int". I want to upload my score either as a float or double since they have a much larger max value. Once players get far in my game they will eventually get a score over 1 billion so this is why..
does anyone know how I could upload my score online as a double?
no
try restart
For a clicker game you'll want to use a big decimal style library for the score and the only real feasible way to store the score will be as a string or byte array.
You'll want to use whatever lootlocker offers for freeform or custom data
+1
hmm thats interesting. I guess I'l have to change lots of things
you'll have degrading precision as scores get larger
yea maybe but this is fine actually
since at one point players will make more than 1 million per click
whats that? on google?
ohh i'l check that out thanks a lot m8
damnn crazy how poeple r doing that
doing what, creating libraries?
can anyone tell me why my code wont spawn an special enemy every ten waves? https://gdl.space/ecehirajur.cs
Use debug.log and print out your variable values
See what's going wrong
Also check if the code is running as expected
Time to start debugging
https://paste.ofcode.org/sHyTXzdL6hPfwF2XFL2KY3
I have the following code where in the start screen(containing text and dots), the user presses on the screen "tap to start" to begin the game. Once this happens, I want to instantiate all the objects with the tag of "Dot" with a 0.25 second interval. So the user starts the game, the dots and text from the main menu disappear. Then, the objects with tag "Dot" get instantiated with 1 second interval. Note that the dots on the main menu and the dots that need to be instantiated are the same.
Okay, and what's wrong?
there is no time delay when i press start to play
the dots all instantiate at the same time
That's not how coroutines work
Coroutines can only delay themselves
They aren't going to do anything to delay the code that called StartCoroutine
It seems like it would be inconvenient to keep the chunkdata data consisting of 10m, 10m in the array :D, do I need to learn sqlite etc. to keep and store such large data
ello lads. what i've got going on is a first person game, and i have an object that is parented to the camera to act as a placeholder for where the player can pick up an object an drop it. i'm trying to make it so when i scroll the mousewheel, the position will move further away or closer to the camera, but move related to the camera. i've managed to get the object to move, but i don't know how to go about making it move relative to the camera. i have one idea that i feel like could work, but it would be very roundabout and i know there is a simpler solution, but i don't know what it is :V
if (Input.GetAxisRaw("Mouse ScrollWheel") != 0)
{
HoldPos.transform.position += new Vector3(0, 0, Input.GetAxisRaw("Mouse ScrollWheel"));
}
HoldPos is the game object that is parented to the camera. i've programmed it so any object you pick up with have the same position as HoldPos
edit: damn, localPosition is all i needed to do
Can someone explain to me why this happens? 
[CustomPropertyDrawer(typeof(BaseTriggerMechanics), true)]
internal class BaseTriggersDrawer : PropertyDrawer
{
// Used to add some margin between the the HelpBox and the property.
private const int margin_height = 4;
// Global field to store the original (base) property height.
private float base_height = 0;
private const float indent = 18;
private bool is_expanded = false;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
if (is_expanded)
{
base_height = base.GetPropertyHeight(property, label);
base_height += EditorGUI.GetPropertyHeight(property);
/*
base_height = base.GetPropertyHeight(property, label);
float field_height = margin_height + EditorGUIUtility.singleLineHeight;
return base_height + field_height * 2;
*/
return base_height + (margin_height + (EditorGUIUtility.singleLineHeight + margin_height) * 2);
}
else return base.GetPropertyHeight(property, label);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
SerializedProperty index_name = property.FindPropertyRelative("name");
EditorGUI.BeginChangeCheck();
is_expanded = EditorGUI.Foldout(position, is_expanded, index_name.stringValue);
if (EditorGUI.EndChangeCheck())
{
/*
position.y += margin_height + EditorGUIUtility.singleLineHeight;
position.x += indent;
position.width -= indent;
property.NextVisible(true);
EditorGUI.PropertyField(position, property);
*/
}
}
}
probably better off asking in #βοΈβeditor-extensions
where can i ask questions about unity devops?
I guess because you have a margin of 4
What would be the right approach for loading an external file in my game? Is it even possible to load a file that is not in the resources?
You generally can load stuff from anywhere (file io, network requests) and convert them to Unity types at runtime.
Heyo, I am trying to connect an Arduino Code where I extracted some float numbers out of some Flex Sensors, and I am trying to "connect" these numbers to a hand animation in unity, but i am completely lost. Does someone know some stuff about this to help me out? π₯²
I'm thinking you could do that with a serial port?
I did a similar type of thing, not in unity just printing to console and serial port worked.
Not sure if unity or c# has a way of reading serial port, I'm pretty sure it does.
This looks like what you're looking for in terms of unity side of things, and for the arduino side you'd just need to write the data to the port in some way you can read again.
I am trying to use Serial Port using a c# Script, but I am getting tons of errors for some reason.
using System.IO.Ports;
public class HandController : MonoBehaviour
{
public string portName = "COM3";
public int baudRate = 9600;
public Animator handAnimator;
private SerialPort dataStream;
void Start()
{
dataStream = new SerialPort(portName, baudRate);
dataStream.Open();
}
void Update()
{
if (dataStream != null && dataStream.IsOpen)
{
string[] fingerData = dataStream.ReadLine().Split(',');
if (fingerData.Length == 5)
{
float indexValue = float.Parse(fingerData[0]);
float middleValue = float.Parse(fingerData[1]);
float pinkyValue = float.Parse(fingerData[2]);
float ringValue = float.Parse(fingerData[3]);
float thumbValue = float.Parse(fingerData[4]);
handAnimator.SetFloat("Index", indexValue);
handAnimator.SetFloat("Middle", middleValue);
handAnimator.SetFloat("Pinky", pinkyValue);
handAnimator.SetFloat("Ring", ringValue);
handAnimator.SetFloat("Thumb", thumbValue);
}
}
}
void OnDestroy()
{
if (dataStream != null && dataStream.IsOpen)
{
dataStream.Close();
}
}
}```
That's the C# I've used
Cool, what's the error?
"IOException: Access is denied."
Are you sure the port is actually open?
Wait, lemme quickly run it again and maybe make a screenshot of the error.
Actually, might be simpler than that?
If you're running the arduino sketch thing and reading the serial port data
As far as I know, only one application can use a serial port at a time.
So I should try closing the Arduino Program?
(Someone else can correct me on this if I'm wrong, but I believe that's correct)
Yeah, try it
Just make sure the sketch is uploaded to the arduino
How do I have support multiple controllers using the Input Manager in Project Settings? I am using Unity 2020.3.48f1 for my project.
Still isn't working.
Access denied still?
Yeah
Now I also get this error : ```FormatException: Input string was not in a correct format.
System.Number.ThrowOverflowOrFormatException (System.Boolean overflow, System.String overflowResourceKey) (at <88e4733ac7bc4ae1b496735e6b83bbd3>:0)
System.Number.ParseSingle (System.ReadOnlySpan`1[T] value, System.Globalization.NumberStyles styles, System.Globalization.NumberFormatInfo info) (at <88e4733ac7bc4ae1b496735e6b83bbd3>:0)
System.Single.Parse (System.String s) (at <88e4733ac7bc4ae1b496735e6b83bbd3>:0)
Hand.Update () (at Assets/Script/Hand.cs:28)
I think you might actually be getting data
Are you constantly instantiating a new version of this?
But is somehow converting it wrong?
Or is it just one instance throughout
If you're rapidly opening and closing the port you'll get problems
Welp the USB is always on, haven't took it out once.
Oh
As far as I know, I do not.
Idea

