#archived-code-general
1 messages · Page 158 of 1
hm it may be possible to use a single shader with triplanar and 3d texture even for this case
I was thinking about generating some surface geometry like little pebbles depending on what it is
probably a second renderer
that sounds like something you dont need to bake
(and also can be done on the shader)
Oh yeah, maybe a compute or vertex shader
There was one by i think AstroCat that looked very clean and was interactive
It would require some modifications to work with multiple players though
This looks very nice too
doubt debris and clutter need to be syncd
Nope, at this point its only the byte array underneath everything
how its drawn can be on the client side
Any easy way in C# to give named values to the result that comes from an array like this?
(string caller, string func) = token.Split(".");
Essentially, I want to avoid using result[0] and result[1] and give them more meaningful names all in one line.
how pythonic of you
Precisely
I don't think so, short of modifying the function to return a tuple
I've been bouncing between them and am saddened it doesn't work this way in C#
which you obviously can't here
Yeah, just wondering if there's anything I can do it because this error seems promising:
It's just that string arrays don't have a Deconstruct operator
Wondering if there's a namespace that gives it one?
in Go there's a convenient Cut function which is great when you know it's only going to be split in two:
https://pkg.go.dev/strings#Cut
idk if C# has that
you could write one with IndexOf and Substring
what can cause a pod which has [SerializeField] string guid;
with ISerializationCallback,
to have a value in editor, but at runtime the string is empty?
its a scriptable, debugged, value is present in editor,
at runtime in OnAfterDeserialize the string is empty
Eh, I'll just use two lines. No biggie I guess.
i need some more help. in my game you fly in the sky. i want the creatures that live in it to move even when you're not moving. like you can stay still, but the animals still move. how would i do that?
Why would you be moving have any effect on other things moving? That's something you'd need to go out of your way to implement
So if they don't move unless you're moving and you don't want that, get rid of whatever you did to make them do that
public static (string, string) Cut(this string s, string splitOn) {
int index = s.IndexOf(splitOn);
if (index >= 0) {
return (s.Substring(0, index), s.Substring(index + 1));
}
return (s, null);
}``` Or you could write 6 lines!!!

i see, i didn't even implement it yet, i was lost on the first step lol
mistery, i can see in OnBeforeSerialize that the string is set to a value, at runtime its gone
nah cause .Split() doesnt return a specific number of items, it can return anywhere from 1 to n items
Yeah, makes sense. In Python if you do that sort of tuple deconstructing everything it doesn't have an output value for just gets discarded. That's probably too loosey-goosey for a big boy programming language that can actually become machine code on its own
you can just do s[0..index] now :3
the best part is that you can do [n...^1] which is ❤️
The only one I'm proficient with is s[^1]
yeeee, I was so hype when that functionality was announced
no more myString.Length-1'ing
Since I have both of you two here @leaden ice @naive swallow either of you ever seen this before?
#archived-code-general message
its really harshing my workflow when like half my stuff gets underlined as a warn/error when I have explicitly setup my editorconfig for it to be ignored :/
I'm far too much of a peasant to have Rider
same issue on Visual Studio too O_o
its like the IDEs are loading the .editorconfig file... and then promptly ignoring it in the actual editor o_O
I have not and to be honest I've never touched something called an "editorconfig" file
not even sure what that is
when you click these bois, it generates the .editorconfig file which customizes what error severity various things are
can't you just disable those inspections in Rider?
there's a lightbulb thing in the bottom right
thats what that is yeah
thats what the editorconfig file is 🙂
it does yup, right next to the .sln and .csproj files
it can actually even go lower and the rule is a .editorconfig applies to any files at its level or lower
alright well, I'm not sure 😉
so you can even add a second .editorconfig file in say, /Assets/Scripts/Foos and it will "override" all settings for the Foos folder and lower
or at least... its supposed to
but for me none of my editor configs seem to actually be applying, but resharper and VS show it as loaded and the settings as applied in both of their Preferences menus
like if I open my Code Style in Rider, you can see it is indeed "seeing" the .editorconfig file
but then its just... not actually applying in the editor itself, its so weird
I feel like somehow Unity is at fault here, like its somehow messing with this or something
cuz it works fine in a normal dotnet application, it is only an issue for Unity projects O_o
could be
unity does all kinds of things with the cs project
have you double checked that your Rider integration is up to date?
yeah just installed it yesterday evening
issue is for both Rider and Visual Studio tho :x
like they both have this same weirdness
probably both packages are bugged
¯_(ツ)_/¯
im still on a very old vs package because new ones break 2019
tried to fix it myself but at some point just decided that fuck it
rider one isnt by unity tho right?
Hey
headTrans.rotation = Quaternion.Slerp(headTrans.rotation, value2, timeCount * 3.5f);
if(headTrans.rotation == value2)
{
Debug.Log("PASSEI");
secondTime = true;
timeCount = 0.0f;
}
For some reason
SOMETIMES headTrans is, and sometimes it's not value2
Any idea?
Slerp will not give you exactly the second parameter ever unless the third parameter is >= 1
do not compare with ==
do something like
if (Quaternion.Angle(value2, headTrans.rotation) < 0.01f)``` for example
it's not a unity thing
it's a simple math thing
Yeah, but i'm not familiar with a function i cannot read how it exactly works.
If you go some percentage between a and b, you will never reach b
ever heard of Zeno's paradox?
I'll test this soon, thanks for helping me
Slerp/Lerp are basically functions that say "move x% from a to b"
so you will never reach b
unless the percentage is 100%
the only exception would be that you go so incredibly close you actually got there due to floating point imprecision
So I'm trying to make EventArgs work, but now I'm wondering if that's even the right things to do for what I'm trying to achieve. Endgoal: Make it possible to transfer multiple parameters through a UnityEvent in the inspector.
Like, I want to pass a string and a bool value, to interact with this: ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class EventChecks
{
public static Dictionary<string, bool> checks;
public static void InitializeChecks()
{
checks = new Dictionary<string, bool>();
checks.Add("testCheck", false);
}
public static void SetCheckValue(string checkKey, bool checkVal)
{
if (checks.ContainsKey(checkKey)) return;
checks[checkKey] = checkVal;
}
}
- This isn't going to solve your problem
- EventArgs is a poor pattern for Unity due to memory/garbage collection
UnityEvent only supports one parameter
you can't change that
dang, so what do I do in this case?
Simple workaround is something like this:
public string s;
public bool b;
public void DoSomething() { // call this from the UnityEvent
SetCheckValue(s, b);
}```
So basically, another component handles the actual event. That makes enough sense, at least.
could be another component, could be the same one
I was just wondering if there was a way that I wouldn't need to do that, but if it's the best way ...
the point is just delegating the parameters from elsewhere
wait one other thing here
are you setting these parameters statically (in the inspector) or dynamically?
e.g. by calling myUnityEvent.Invoke(x, y)
if it's the latter you should be able to do it just by declaring your UnityEvent as UnityEvent<string, bool>
fi it's statically (in the inspeector) you must do a workaround like I shared
I wanted to have a UnityEvent that would call this: public void SetEventCheck(string key, bool value) { EventChecks.checks[key] = value; }
yeah that's not what I'm asking though
I'm asking how you are sending the parameters into it
from the inspector, or from code?
like where is the UnityEvent defined and invoked?
Typically I set it up so I can send the parameters from the inspector, for workflow reasons.
ok so if you want the inspector you are stuck with the workarounds
what's the other methods?
public UnityEvent<string, bool> myUnityEvent;
void FireEvent(){
myUnityEvent.Invoke(someString, someBool);
}```
in this case the parameters come from the code somehow
of course you could then set someString and someBool separately in the inspector for this component
I think I do that for using V3s as spawn coordinates for a warp event. I set up coordinates and call upon the corresponding index for that.
It's just likely to get more cluttered if I try to do it with variables ...
unless I have events that change the variable index before invoking an event that changes the value ...
that way I could do everything without additional components, it'd just be a couple more events each time I want to change a check's value
frankly I'd like to work with someone to take a look at the event system I've made so far and just learn if there's a better way to do what I'm trying to do. My current method is just queueing unityevents to fire in sequence ...
My EventManager: https://pastebin.com/Xdm5YaCW
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
My OnMouseEnter code not working in some GameObjects. But it works in copy of the game object I use. Only different is their position.
How can I solve that?
@karmic zealot Can I see your code?
do you have a collider?
Yes
what objects does it work on?
How is this posible?
The hex vertices are rendered using the position
the position is the center,
how come to 3 direction arrow is not properly centered on the hex?
I'm trying to select something
ohh, a selection, got it
is something wrong
I'm not sure ...
I'd ask to call to better see what's happening but I'm not in a situaton where I can atm.
what is in the scene? Can we get a view of that?
is the mesh origin set up correctly?
When I change it's position it works
Or when I change its colliders trigger setting
Works like a charm
Thanks sire
what do you mean?
Again, it would help to see what's actually in the scene itself
where did the hex mesh come from?
Where is the origin of the 3D model? Is it correctly in the center?
how is it hex shaped
is that through a shader? Or what
quad
vertices
yes
so that is the vertex corner
public static Vector3 GetPosition(int x, int z)
{
Vector3 position;
position.x = (x + (z * 0.5f) - (z / 2)) * (HexMetrics.innerRadius * 2f) + (x * step);
position.y = 0f;
position.z = z * (HexMetrics.outerRadius * 1.5f) + (z * step);
return position;
}
you pass in coordinates to get spawn location
where's the code that modifies the mesh
wait also before we go down this rabbit hole too far:
Is your tool settings set to "Center" or "Pivot" on the left here
oof
it should be on pivot
is it on pivot now, or center?
if you changed it to center, that's still a problem
now its on center
also this code only seems to clear the mesh
it's not adding any vertices or anything
except to this "Vertices" list which seems unused here
ok so where does "CombineVertices()" come from
maybe just show the whole script
in a paste site
Center position = Position = "(4.33, 0.00, 7.50)"
you sure, its 700 lines?
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
there u go
This is from another class, but here is how the hex are spawned
Also, the vertices are well made
ok here's your problem:
for (int i = 0; i < 6; i++)
{
Vertices.Add(VertexCorners[i] + Position);
}```
you should not be adding Position here
because in the mesh, the positions should be in local space
not world space
The mesh should be positioned by its Transform
likewise this way you can share a single Mesh for all of the hexes
uhhh
ironically, that is what I did before hand
the problem however was its very hard to get the position of the surrounded hexes
I did eventually figure it out, but another thing was that since my shader relied on the position(notably) the Y position of vertex to color it
my shader was always wrong
Here is an example
if you want to create slopes between the hexes, you will have to spread them out and link them together
however since the position are all local, you have to do some trick math to get them
I'm not sure about all that but the transform.position is where the gizmo will be
in the shader you can get the world space or local space position of the vertex
whichever you need
mul(unity_ObjectToWorld, v.vertex)
or uhh float3 worldPos = mul(unity_ObjectToWorld, float4(v.vertex.xyz, 1)).xyz;
Are you doing any Editor scripting?
False positives. Those aren't your code.
...what?
You didn't write the lines of code. They're likely not relating to something you've done. It isn't an issue you can fix by coding.
ok
I have the following code that adds unique identificators in my objects. But I've stumbled upon a problem: it fires up on a prefab even when I just select it in the browser. Which results in every prefab I place in the scene getting same GUID.
I tried to set field to "0" when I have asset selected in the browser - it just instantly generates new GUID.
While I want prefabs to get unique IDs, but only when I drag them into the editor OR instantiate them in the game, and not when I load level or do anything else (Supposedly this should be prevented by the check that GUID isn't empty before trying to assign it. It is for my save game system, persistent level states and serialization, so I need them to be as static and invariable as they can be).
How can I fix my code?
public abstract class DynamicObject : MonoBehaviour, ISaveSystem
{
[SerializeField]
internal string objectID;
internal void OnValidate()
{
if (!Application.isPlaying && !EditorSceneManager.IsPreviewSceneObject(this))
AssignGUID();
if (PrefabUtility.IsPartOfAnyPrefab(this))
PrefabUtility.RecordPrefabInstancePropertyModifications(this);
}
/// <summary>
/// Assign GUID to the object if it doesn't have one already
/// </summary>
/// <param name="force">Normally, GUID will be assigned only if the field is empty. This will force new GUID to be created no matter what.</param>
internal void AssignGUID(bool force = false)
{
if (objectID == String.Empty || objectID == "0"|| force)
objectID = Guid.NewGuid().ToString();
}
Would anyone happen to know of some resources that could help me get started with implementing a system to prevent distance objects from being active and activating them as the player gets close? I'm looking to implement a large Maze game with no area transitions ideally. So I presume I need a system in place to activate entities and other scripts as the player approaches rather than having everything loaded and running.
You could do a global game state singleton (if you do not have one already) with a List of game objects, and make it iteratively check distance from player to every object in that list every second of 5 seconds (depending on how fast your player can move and how long straight paths are in your maze), turning them off and on depending on the required distance, and then all objects that should be culled in this fashion add themselves in that game manager list upon Start();
Alternatively you could make that list sit in the player script itself, but this is not a good way to do it.
Can you even pass around "plain classes" in the inspector? Can they be assigned as a component? That's a fundamental question I came up with. If not, I see not point in using a "plain class"... maybe everything should be a Monobehaviour. Initially I thought "plain classes" are clever to encapsulate data. But it seems they cause more problems than they're worth.
Non mono classes cannot be used as components in the editor, no.
The point of MonoBehaviour is that it's how you create a custom component
To clarify I'm asking about keeping a reference to plain class in the inspector. Otherwise I have to instantiate this plain class separately in each component.
if you aren't making a component, you don't make a MonoBehaviour
But let's say I want to store player health in a class like public class Player{ int playerHealth; } .... when I create new Player() can I pass that around in the inspector somehow? Except by passing around in code.
I cannot have 2 components using one instance of this plain class, right?
Any class can be instantiated as many times as you want, unless it needs to be static/singleton. Are you trying to access the health for reading the player's health from things other than the player?
Let me prepare another example maybe
[Serializable]
public class Player {
public int playerHealth;
}
public class Component1 : MonoBehaviour {
public Player player;
}
public class Component2 : MonoBehaviour {
public Player player;
}
If I do this, each component will have its own instance of Player object, right?
If I edit values in Component1, then Component2 will have a separate set of values
Yep
Ahh you want dependenciy injection I suspect. You want to store the player health in one central location, and access it from other components, correct?
Forgot [serializable]
In that case, yes
So, now, is there any other way to do this, except to turn the plain class into a component, and attach to a Gameobject? Like so:
public class Player: MonoBehaviour {
public int playerHealth;
}
public class Component1 : MonoBehaviour {
public Player player;
}
public class Component2 : MonoBehaviour {
public Player player;
}
Now it should be only one instance of Player, right? If assigned using the inspector
So if the class wasn't a MonoBehaviour you'd do something like this for the Constructor public MyClass(IPlayer playerData). However, due to component framework of unity, you can't get access to the constructor to implement this easily. You'd typically want to implement a "Singleton". There are some issues with doing this, as it gives allot of things access to a set of data which is not usually ideal but it is something done to overcome unity's framework without having to use something like Zenject.
There are some really good videos that taught me about this, as I've run into this question allot eairly on.
I'll grab some links.
https://www.youtube.com/watch?v=mpM0C6quQjs implementation and good overview here.
Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP
The Singleton Pattern is a design pattern that's well-loved by Unity game developers. But, unfortunately, it has some serious drawbacks that most programmers don't discover until it's too late. In this video, I'll show you what those drawbacks are so you can avoid them in the...
Basicly you have like a GameObject called "GameManager", game manager contains a component monobehaviour containing the data you want to access. You write some code into the awake function that ensures that when the class is instantiated, it is the only one and sets itself to a public static on the class itself (Component1.Instance). Then you can access that data via that reference i.e Component1.Instance.Player.GetHealth() or something like that.
Thanks. Although 80% of this video says not to use singletons xD
singletons are kind of a flashpoint for developers, I think because the idea of making something publicly available anywhere is not considered good code professionally. However, for smaller, idie games it should be acceptable so long as you are aware of the drawbacks and concerns. https://youtu.be/iQvCGHPomr0 goes more indepth why it could be ok to use Singeltons.
The first 1000 people to use the link will get a free trial of Skillshare Premium Membership: https://skl.sh/jasonweimann03211
Are singletons really that bad? Let's discuss why they might be somewhat helpful in your unity3d game, what some of the issue can be, and how you can apply the singleton pattern in your games.
Check out the Course: htt...
sometimes u do need them, his example really didnt make too much sense though. A singleton means you have one, but then his counterpoint was saying "now what if you have an armored player?"
Which either isnt an issue or that just means the singleton never made sense to begin with
its something you should just use if theres only ever supposed to be one. Like a save system is a good example, you dont need 2 different scripts saving to your one pc. Another example i use in my game is a checkpoint system, each level only has 1 list of checkpoints but thats per design
why do gameobjects move when they're inactive?
is this gameobject perhaps a child of another moving gameobject
What do you mean? You're allowed to modify it and whatnot but it shouldn't be visible etc
i don't mean it actively moves. i mean that when the gameobject is active, it's in one place, and when it is inactive, it is in another place.
then you'll have to show your code, because you are leaving a lot of detail out
You're going to have to show us what you mean because that likely isn't the case
i can guarantee that if i open a new project, put a cube in the scene, toggle it inactive/active, it wont have moved
if it does then ill need an exorcism, which isnt a code issue
and this is true
suddenly it fucking moves
also, in the editor, the rifle appears here. right in front of the camera
when you PLAY, it moves
and only the mesh moves! not the arms! which are both children of the same gameobject!
i really dont get why you're sending screenshots, all i asked for was code. The first 2 images literally show that your object's local position doesnt move
meaning that your parent is moving
very new to unity, don't know what info to provide :)
Do you rather have separate action for each event type or have enum for that?
A)
public delegate void EntityClickedAction();
public event EntityClickedAction OnPlayerClicked, OnBuilderClicked, OnEnemyClicked, OnAnimalClicked;
or
B)
enum EntityType { Player, Builder, Enemy, Animal }
public delegate void EntityClickedAction(EntityType type);
public event EntityClickedAction OnEntityClicked;
Personally for me the giant drawback for B) is that you need a giant switch statement to handle that. And in A) you can have neat little methods with handlers for each type.
figured it out. accidentally added an animator to the mesh
well these are delegates, not actions. Id say it depends though on what you want. Do subscribers care about if a "Player, Builder, Enemy, and Animal" are all clicked? Do they only care about one or a smaller subset?
It can be fine to have a lot of events, I would just look at adding your own custom add/remove function because I believe every event would be allocating for every instance of this class. Instead you could just have it allocate when something actually cares to subscribe to it since a lot of events often go unused
Is there a way to make a public variable be of type ParentClass, and assign ChildClass (inherits from ParentClass) to it?
do you mean just
ParentClass varName = new ChildClass();
that should be fine by itself
is there a way to do that from the editor with public variable?
dragging ChildClass to a ParentClass variable doesn't work
@lean sail
really all I can say is that it does work
because you havent shown much about your project
Hmm, it should. Unless you are talking about interfaces, which it sounds like you aren't
I have an Attack class and a Player that needs to reference an Attack, and the different attacks inherit from Attack. I need to reference that inheriting class for the attack.
Interfaces meaning the editor?
no, like a c# interface
am i wrong to hate the inspector for connecting up objects? I feel that it creates an unsearcbable coupling.
show what you're actually doing, because still this is just a high level description.
I'm trying to drag a c# script that inherits from Attack from the Project window into here
maybe i can search the inspector for the couling? code makes it clear to me and is search able
so if i where to say that all couling should happen using code in the future if at all possible, that wouldn't be too strange, right?
how would you get around the case where 2 instances of 1 script needs different scripts plugged in? You'll just be adding more code for no reason
i see
that is a good point that i didnt of.
so there is a case where using the inspector isn't worse
good to know. thank you
so outside that case i would be well served with my ruling?\
is this object in your scene? can you please not crop screenshots, id rather see a large screenshot telling me more info so i dont have to play 20 questions
I'm trying to drag StaticAttack into Main Attack from the bottom Project window
It's not in the scene
Well the player with the main attack isa
but not the StaticAttack script
you can do whatever you'd like, but sometimes using the inspector is just easier. If its a difference of GetComponent<> in awake vs dragging it in the inspector, no ones gonna really fight you on that.
And also for level design, some things really are just easier to drag in the inspector. Like if you have a button that opens a very specific door, and lots of these button -> effect things, then it'll be hard to set this up through code when something like unity events already exist.
well 2 things: you cant drag an actual c# script into that field, its asking for a component (on a gameobject)
and it has to live in a scene, since it has to be on a gameobject
but there is no way to search the inspector for the links, i just have to remember them?
The inspector just displays things, it doesn't functionally affect anything. It's a tool to bypass a lot of boilerplate. You can find anything connected through the inspector using code like normal.
the inspector shows you the links
but if i have a ton of object how do i find something someone else did in the inspector and didnt document?
if your system is complex to the point that you're going through 50 gameobjects linked together, you probably need to change something
thanks i put the script onto an empty object and it works
i hate that i can have an object selected and i cant find where it's been inserted into the other obejcts
unless i can and i dont know how?
well I dont think thats what you want, it should probably be on the player. At the same time, its kinda odd to have all these attacks just sitting on the player as monobehaviours
i think it'll be fine but ig i'll see
thanks for the help
the closest thing I know would be right clicking a component and pressing Find references in scene
snap. where is that button?
exactly where i said itd be, you right click a component and press Find references in scene
doubt you'll really find much use in this though, if you dont know what an objects purpose in the scene is
i dont see it
so i can't see where it's been dragged into something
For the actual gameobject im not sure. For the components of an object, you can
right
thank you for your help
as a noob to unity this would be a great feature
as is i tear my hair out
You should probably not ever be referencing the game object as type GameObject but instead as the specific component type. Unless you're simply changing the activeness or name...
@dusk apex i wish i understood what you meant
it sounds like you are saying dragging game object into components willy nilly is a bad idea
which is my thesis
If it's the correct component type, it'll take the reference as the specific component type
hmm, still not following
sorry
what i am trying to do is make my code/project more understandable and searchable for all the coupling that exists because the coupling seems a lightmare now in my project
Reference the game object as the specific component type
Generally, you know what needs to be linked and referenced for your objects. You mainly drag references from the same GameObject or its parent
You wouldn't randomly have GameObjects referenced in a bunch of other GameObjects (scripts). That really doesn't make sense . . .
This is relative to code. You can drag whatever you're wanting into the slot. It'll only accept something with the specific component type.
Curious, what about it seems nightmarish?
Then you'll be able to find references of the component etc
I'm not sure why you guys think they are referencing gameobjects instead of, say, text? Did I miss an inspector photo?
They have like 30 text objects in the scene and don't know where each one is referenced. That would be the same issue if they did public gameobject or public text
Which is an architecture/organization problem hahaha
I can search the code for this connection: bookmarkplus = GameObject.Find("boomarkplus").GetComponent<Button>();
i cant search the ui if do it as far as i can can tell
They were saying find reference using the inspector wasn't applicable because they would like to search using the Game Object in scene. I'm sure either they're misunderstanding how component reference works or are simply referencing Game Objects, which they should not be.
there is something sublte going on here that i am not following i think
Everything in the scene is attached to a GameObject. I asked what their nightmarish problem was bcuz I only saw them ask about linking and coupling objects in the scene . . .
as is i dont like changing the scene if i can do it in code because then its search able and i dont have to worry avbout merging the .unity files
If you type public Button play in code and drag the button object into the inspector field. You're referencing the Button component and it can be searched for via component using what was previously suggested.
that is where i am, but it seems there is a higher plane of existance i am missing out on
Well, i know that...
I was talking about what dalphat is saying, because they seem to be thinking the opposite of what the actual issue is.
John wants to search which component references this object which has text on it. Instead of which text does this component field reference.
Which would be the same problem no matter what type the field is.
Does that make sense?
i'm not seeing that and by god i want to
Dalphat is saying search via the field in the INSPECTOR, instead of the hierarchy like you're trying
Which is a perfect solution to what you want, just reversed
To explain a little more clearly, I assume you have text fields in foreground maybe? Select that in the hierarchy (on the left). Right click that field (the box you drag things into) in the INSPECTOR (the one on the right) and click find. It will show you which object the field is referencing (regardless of the type of the field)
Hello everyone. For some reason I can't get AddListener to run.
This is the event: https://hatebin.com/slavumfptr
And this is the listener: https://hatebin.com/fnjdwjsrhr
The "Messenger" is referenced in Item's parent class.
how does the smooth variable work in lerp functions? i never really understood it
Did u debug if the event is ever being invoked?
Yes. The event itself works. If I add the Item via the + in the inspector, it all works as intended.
I can't do that though because the item sits in a separate scene that gets loaded additively.
If the listener isnt working, it's probably not taking the correct instance of Messenger then
And sorry for forgetting comments. The relevant lines in the first script are 17 and 51.
Hm. The parent class grabs the Messenger based on a tag and also finds it. And there's only one Messenger.
Hi, I have an UnityEvent, and I want to call a function
public void MyFunction(MyEnum enum) but I don't seem to be able to select it in the inspector. Can you not call functions with enum parameters with a generic UnityEvent?
I dont see any issue with the code, and the part where grabbing the instance is not in these classes so it might be an issue in finding the messenger. Or maybe its awake hasnt run when the event is invoked
I could do UnityEvent<MyEnum> but that doesn't let me select the value of said enum in the inspector, which is what I need.
I have set MyEnum to Serializable
This is the parent class: https://hatebin.com/gfjmamrczk
Bump
Maybe try using a singleton instead of tag searching. At least itll guarantee theres only 1
Otherwise I'd just suggest running through the debugger
You'll see all the values that way
i hate that ||i can have an object selected and ||i cant find where it's been inserted into the other obejcts
You can find all objects that have referenced the component.
Not sure where you're getting
Instead of which text does this component field reference.
from though
What I'm referring to.
Yes.... i know that. But he was trying to search from the HIERARCHY.
I put AddListener into CustomStart() and now it works! I'm sure I had it there before I tried Awake(). Hm. Maybe it works sometimes and sometimes not because of some initialisation weirdness. I'll check. Thanks!
So I just read between the lines
Lets not muddy up the channel though. He's gone, and it doesn't really matter anymore unless they come back
He simply misunderstood what was advised.
I believe that actually finding the objects that are referencing the instance is what what's wanted and that by searching via component, it will work.
Thus why I brought up how is not likely or wanted to reference something as type GameObject (unless you're really wanting no other feature) and that searching via inspector-component would be perfectly suitable.
Yes... that was my whole point. He misunderstood what was being suggested, so we had to come to his level and redirect him....
But w/e. Again, it's not relevant anymore. Have a good one
whoops not code
Can you overload the instantiate call to create and set a new guid for the new object?
ah typically you would do it on Start(), where you leave Awake() to be for self initialization. I assumed it wouldnt be an issue since you would probably get a null error and you said this object was spawned later
Oh here i think you can use this to determine if the context is the prefab rather than instance if (!PrefabUtility.IsPartOfPrefabAsset(gameObject) && !PrefabUtility.IsPartOfPrefabInstance(gameObject))
{
You are negating both. Shouldn't the second check be true? If you want an instance.
Never used that though, so i dunno
I think you are right, I haven't used it either, would need to test it works as expected and probably have an editor only directive too. Hopefully though it will let the OP determine if its the prefab and set it to empty, then on start/awake/onenable create a new guid if empty, or something like that.
you can't because your custom enum is not a base type or doesn't inherit from UnityEngine.Object. you can just create a class field of your enum type and select the value you want, then use that field when the method is called from the event, or
use an int (enums are named ints) and cast it back to the enum where the method is called. then you can set the integer from the inspector . . .
ugh, such a silly workaround. Neither exactly works for me.
Unity HAS a proper enum selector, and it's amazing. Why don't they just use it there? that's ridiculous.
Thanks, PrefabUtility.IsPartOfPrefabAsset(gameObject) just did the trick!
because it's not a primitive type: int, float, string, bool, etc. . . .
I assume UnityEvent is using reflection, to get the functions and arguments, when selecting what to call. It is 100% possible to tell apart an enum field from an int or a string field, in the function parameters, with reflection. They need to create an input field in the inspector for that particular parameter anyway. Different one for a string, different for an int, different for bool. Then why didn't they add an enum one as well? That's just such a missed opportunity.
also. int, float etc. all derive from ValueType, which derives from Object, the C# class.
System.Enum, which all enums derive from, also derives from ValueType, so yes - it seems to be a primitive, or at least pretty similar
Looking for help with A* Pathfinding
I presume they haven't done it because an enum can be any type of integral type and they don't want to add some more logic to figure out what needs to be serialized, but I agree it can be done and probably should be done, at least for enums that use int as their backing type.
enum is not a primitive type (data types built into the language) as any "custom" enum we create must derive from enum. we do not derive from int, float, string, bool, etc., to create our own variables. yes, it's a value type, but that does not denote it a primitive type. a struct is also a value type but it's not a primitive type. an anum can have flags, be used as bits and represent multiple integral types
as you can see under the hood, the PersistentListernerMode selects the type of primitive to use for the argument, then Arguments assigns the value as it only consists of the primitive types that can be used within the inspector for events . . .
C# has a property for that if you want to verify yourself.
typeof(Enum).IsPrimitive;
Hey guys I have this code which is basically to iterate through a dictionary of items with a decrementing timer as the value property in the dictionary. When the timer hits 0, I want to remove the kvp from the dictionary, but I cant modify a dictionary while enumerating through it so I add the values to a list which I then remove and clear afterward.
public void DigestiveSystem()
{
foreach (KeyValuePair<PlantBehaviour, float> plant_kvp in plants_consumed)
{
plants_consumed[plant_kvp.Key] -= Time.deltaTime * ecosystemScriptableObject.tickspeed;
if (plants_consumed[plant_kvp.Key] <= 0)
{
to_be_removed_plants_consumed.Add(plant_kvp.Key);
}
}
RemovePlantsFromDict();
}
public void RemovePlantsFromDict()
{
foreach (PlantBehaviour plant in to_be_removed_plants_consumed)
{
if (plants_consumed.ContainsKey(plant)) {
plants_consumed.Remove(plant);
Destroy(plant.gameObject);
}
}
to_be_removed_plants_consumed.Clear();
}
For some reason, this is still telling me I'm trying to modify the dict while enumerating through it, i.e. InvalidOperationException: Collection was modified; enumeration operation may not execute. Any ideas as to how I could correct this?
Because foreach iterates over the entire collection . . .
foreach (KeyValuePair<PlantBehaviour, float> plant_kvp in plants_consumed)
{
plants_consumed[plant_kvp.Key] -= Time.deltaTime * ecosystemScriptableObject.tickspeed;
You are writing to the collection during a foreach, you can't do that
Just fyi, string is not a primitive. It can be massive and stored on the heap. All primitives are allocated on the stack
void HitTarget(Vector3 pos)
{
audioSource.pitch = 1;
audioSource.PlayOneShot(hitSound);
GameObject GO = Instantiate(hitEffect, pos, Quaternion.identity);
Destroy(GO, 5);
}
``` uh my audio isnt playing. anyone know why? this function is 100% being called by the way.
and my computer speakers are fine
and its assigned
Thanks gentlemen, appreciate the extra set of eyes
Try going through my troubleshooting steps, if it's not in it and you find another solution let me know https://unity.huh.how/audio/silence/muted-audio
ok
wait you made this site? cool. has helped me a lot 🙂
oh i acidently clicked mute audo
may bayt
by bad
I'd use a different collection to store and access the values so you can use a reverse loop, or decrement i in a regular loop to compensate for index shifting (when removing an element) . . .
Glad to help 🙂
It's a valuable resource . . .
ye.
i'm trying to use unity events to communicate game logic to my ui using events, is it okay to fire an event every frame (in the update method) or is it bad for performance?
https://dotnetfiddle.net/dQNw7U This works
Test your C# code online with .NET Fiddle code editor.
Its two foreach loops, which isn't ideal if this is going to happen a lot (like multiple times per frame)
This is what I wrote
public void DigestiveSystem()
{
// Loop through main and reduce timers on alt
foreach (PlantBehaviour k in plants_consumed_main.Keys)
{
plants_consumed_alt[k] -= Time.deltaTime * ecosystemScriptableObject.tickspeed;
}
// Loop through alt and reduce timers on main
foreach (PlantBehaviour k in plants_consumed_alt.Keys)
{
plants_consumed_main[k] -= Time.deltaTime * ecosystemScriptableObject.tickspeed;
}
// Loop through main and if timers are <= 0, remove values on alt
foreach (PlantBehaviour k in plants_consumed_main.Keys)
{
if (plants_consumed_main[k] <= 0)
{
plants_consumed_alt.Remove(k);
Destroy(k);
}
}
// Alt is now the correctly updated dict
// Set main to alt
plants_consumed_main = plants_consumed_alt;
}
But its still throwing the error saying I'm trying to modify dict while enumerating through it
Yes, it's a reference type, my bad 😞. Threw it in with the rest of them. Also, value types are only allocated on the stack when used as local variables or method parameters. If declared as a field in an object, it's stored on the heap as part of that object . . .
I meant CAN be allocated haha. But you are absolutely right. They have to be ABLE to, but don't necessarily have to be, and often aren't as you said
Usually UI gets updated when something specific happens, and isnt usually every frame that specific thing happens, what are you trying to do where you might need an event to happen in Update?
updating a cooldown timer
typically, events are used to avoid this. it should only fire when an update or change has occured . . .
but it's not uncommon. input is used in a similar way . . .
what if i want to display the remaining time on the timer?
Another way you can handle a timer is with Time.time, which will tell you the time in seconds, since the scene loaded, you could instead use that to know when your event started, pass the length the timer should run for, and know when it ends by subtracting Time.time from the event time value
this would be much easier if you created a list of a custom class/struct or tuple that stored the PlantBehaviour and the time or create a time field for the PlantBehaviour class . . .
Anyone know if there's a way to make Texture2D CPU-only? (so that it doesn't take up any memory on the GPU. Or is it that way by default? A little confused)
Good call thanks sport
i ended up using a coroutine ty for suggestion tho
that's what i use for my custom timer. i had a tuple of <timer, Action> but ended up adding Action to the timer class itself, though i could have created a class to hold them both as fields . . .
When you make a code block start with three backticks and cs like '''cs (idk how to escape in markdown) and it will highlight the syntax
Which line does it specifically say is causing the problem?
Gotcha thanks, was wondering how to do this, it's alright I'm gonna go back and rewrite it w/ a custom class
oh, forgot to give an example. here is one using a list of tuples . . .
public class EcosystemScriptableObject : ScriptableObject
{
[SerializeField]
private float _tickSpeed = 0;
public float TickSpeed => _tickSpeed;
}
// Some class.
[SerializeField]
private EcosystemScriptableObject _ecosystem;
private List<Tuple<PlantBehaviour, float>> _plantsConsumed = new();
void DigestiveSystem()
{
var (plant, timer) = default(Tuple<PlantBehaviour, float>);
var count = _plantsConsumed.Count;
for (var i = count - 1; i >= 0; --i)
{
(plant, timer) = _plantsConsumed[i];
timer -= _ecosystem.TickSpeed;
if (timer <= 0)
{
_plantsConsumed.RemoveAt(i);
}
}
}
Thanks
That looks like the old System.Tupple
Nowadays you can just do this with valueTupple List<(SomeClass myClass, float myFloat)> and yeah it can't be serialized.. kinda unfortunate
ok so i have a question about using "new" within my Update() methods inside a script.
if i use "new" under Update(), does that mean it will keep creating a whole new variable every update frame? it's not reusing the first one it made?
i'm asking because im trying to actively think about ways to optimize my code
yes it will create the new instance of it every frame
you need to understand the difference between variable and object
variable itself is allocated on the stack, in the method scope, once execution leaves the method the variable is gone
ah
but the object the variable points to is not, it stays in the heap memory waiting to be garbage collected
and by calling new on classes you allocate a new object
which then the variable points to
though that depends whether it's a class or a struct, and where the struct might be declared/stored
doesnt happen with structs, they are also allocated on the stack
struckt can also be (accidentally)allocated on the heap e,g defensive copy
in general doing new Vector2 is ok, no garbage generated, doing new MyClass() will allocate an object on the heap each time, piling them up until gc
aaah!
alrighty then, imma go ahead and take that off of update then. although the terminology for class and struct is still blurry for me, it might be better if i just manage it at start
thank you very much for the info. i've always just been looking and seeing what things did, but i never had a full idea of what happens under the hood when i put it to practice 😅
if you want to unblur it you need to understand the difference between heap and stack memory
they are not different physically, but how it is treated/cleared
structs are designed to utilize the stack mechanics, so they have properties that stem from that, objects are designed to be stored in the heap
there is much more to it, but this is the key factor in why they behave so differently, and why structs dont cause heap allocations and why they are passed by value
ah ok, well im going to google this up and read up on it more. thank you guys for the information 🙇🏾♂️
it'll be good to get a better understanding of how it works behind the scenes ^^
best way in terms of what? its like 2 lines of code
have some central code that reads/writes your json so you dont have different scripts (all implementing the same logic) trying to do this at the same time
🤷♂️ ive never used TextAsset, i just get the file with system io
TextAsset is by far the easiest method if you don't need to write to the file
So, I have a problem I need solving. I have an animation of a little mining guy hitting a rock
Each time he hits the rock, I want him to slowly reveal a rune that is only active when he clicks on the little miner 4 times. When it reveals the rune, clicking on the little miner character shouldn't do anything else. I was thinking that I have some kind of variable that slowly clicks up to 4 times starting at zero, at which point it can be captured for magical power.
How do I do that with a separate code from what I have here? At this point, this code works perfectly well for what it does and I don't want to add to it because it already has so many other animations linked to it.
I feel like I"m going insane!
Think in terms of OOP. Where does that behavior belong to? What object performs it?
Not sure what you mean about unused events? Can't you just remove it if it's not used?
The code is attached to the Sprite doing the animation hence why im having trouble since i want the miner to be clicked but not the rock itself
And since it only links to th3 animation of the miner, i was thinking i of just doing a variable increase thing
Where each increase just changes the sprite of the rock
This is a visual novel so dont worry about other rocks that need to be affected or something
There's only the one rock that gets mined to reveal the rune
if you have many instances of an object, its possible not every event will be subscribed to. Think of a button, you can have 100 buttons on screen and theres a lot of events associated with each one (like onclick, hover enter, hover exit etc etc i dont actually remember more names)
So if you're just subscribing to the on click method, a lot of events are unused but they exist because someone might wanna use them
What's the problem with making only the miner clickable? I feel like there's some context missing that makes it impossible for me to understand your issue...
The code only works to trigger the miner's animation. It doesnt activate additional animations outside of the one its attached to
Isn't that what you want though? To animate the miner and nothing else? Then what's the problem?
That message only makes me more confused.
You should really restart your explanation and maybe attach some video/screenshots making it clearer if you have trouble explaining in words.
The miner is hitting a rock, a seperate object. The rune is on the rock after the miner hits the rock 4 times. I dont know how to impliment
- Every time the trigger for the miner's animation activating, increase "number of times rock hit" by 1
And
- Linking the variable of "number of times rock hit" to different sprites because as the miner hits the rock, the rock will degrade.
The miner script could have a reference to a script on the rock.
Each time the miner hits the rock(on animation event for example), call a method on the rock(rock.Hit()). The method would increment a counter variable on the rock and when it reaches the desired count, activate your rune logic or whatever you want to do.
Hmm
Is it possible to make the reference a new script or do i have to add it to the miner's script?
Wdym by "making the reference a new script". That sentence doesn't make any sense.😣
I see... In button example how would you remove unused events? Isn't it unknown which one will be clicked until it's clicked?
Anyway, how much cpu and memory could be used to be subscribed to a couple of events? 
well yes you wont know which is clicked, but you know which is subscribed to because someone would've called the add/remove function
if its just a few events then it doesnt matter, but i was just saying it because you asked about having 1 event vs many. If you have many and its on many objects, it can somewhat start to be an issue
In a new script ...
Why would you put the reference in a new script..?
Cause as said before, the script on the miner is one used in other objects but i can just make a seperate version for the miner if it needs to be in the same script
hey guys, so im newbie in photon and i have a problem that when i play w/ two players the players swap the controls idk what is the problem can anyone fix that?
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class FirstPersonMovement : MonoBehaviour
{
public float speed = 5;
[Header("Running")]
public bool canRun = true;
public bool IsRunning { get; private set; }
public float runSpeed = 9;
public KeyCode runningKey = KeyCode.LeftShift;
Rigidbody rigidbody;
PhotonView view;
/// <summary> Functions to override movement speed. Will use the last added override. </summary>
public List<System.Func<float>> speedOverrides = new List<System.Func<float>>();
void Awake()
{
// Get the rigidbody on this.
rigidbody = GetComponent<Rigidbody>();
view = GetComponent<PhotonView>();
}
void Update()
{
if(view.IsMine)
{
// Update IsRunning from input.
IsRunning = canRun && Input.GetKey(runningKey);
// Get targetMovingSpeed.
float targetMovingSpeed = IsRunning ? runSpeed : speed;
if (speedOverrides.Count > 0)
{
targetMovingSpeed = speedOverrides[speedOverrides.Count - 1]();
}
// Get targetVelocity from input.
Vector2 targetVelocity =new Vector2( Input.GetAxis("Horizontal") * targetMovingSpeed, Input.GetAxis("Vertical") * targetMovingSpeed);
// Apply movement.
rigidbody.velocity = transform.rotation * new Vector3(targetVelocity.x, rigidbody.velocity.y, targetVelocity.y);
}
}
}
Where do i even put the the reference linking to the rock.
It could be an extending(sub) class with the specific functionality. It could also be a separate script that does only the rune logic.
You'd add the reference as a serialized field, same as you do with most references.
A bit late, but I got everything working. Thanks!
[System.Serializable]
public class Class_A
{
//fields here
}
[System.Serializable]
public class Class_B
{
//fields here
}
[System.Serializable]
public class Class_AB
{
public List<Class_A> class_a;
public List<Class_B> class_b;
public Class_AB()
{
class_a = new List<Class_A>();
class_b = new List<Class_B>();
}
}
Class_AB class_ab = new Class_AB();
Why can I not see class_ab in the inspector? this is inside a scriptable object
Do you actually expose a serialized field of that type..?
because you didn't specify it as public
This is not a serialized field.
by default fields are private and are not exposed
Hello, when I run the code bellow, an error pops up:
NullReferenceException: Do not create your own module instances, get them from a ParticleSystem instance
UnityEngine.ParticleSystem+MainModule.set_startSize (UnityEngine.ParticleSystem+MinMaxCurve value)
var hit = Physics2D.Raycast(transform.position, transform.right, range);
var main = Emmitter.main;
if(hit.collider != null)
{
main.startSize = hit.distance;
transform.localPosition = hit.distance * 0.5f * Vector2.right;
}
else
{
main.startSize = range;
transform.localPosition = range * 0.5f * Vector2.right;
}
In the documentation it says that yuo have to do this it this way (by storing ParticleSystem.main in a variable)
Why does the error appear and how do I fix it?
What line is the error thrown at?
is main a struct?
In the documentation it says that it's not a normal struct
it's something different and I don't need to reasign it
a sort of interface
HEre's the line where the bug happens:
main.startSize = range;
if I do it this way, it doesn't compile as Emitter.main is not a variable
Emitter.main.startSize = range;
I also tried
main.startSize = new ParticleSystem.MinMaxCurve(range);
still doesn't work
Here's a piece of code in a different script that works
var mainSystem = Emitter.main;
mainSystem.startSpeed = speed;
mainSystem.gravityModifier = gravityIntensity;
Emitter.Emit(1);
How can this work and the previous one not?
Is the particle system disabled by chance?
Wait! I think I'm on to something... When I place the Gamobject with this script attached before I start the game, everything works just fine. But when I instantiate it at runtime, something breakes
What is Emitter referring to
Is it a prefab, or is it the instance in the scene
If it's the prefab that'd be why
a prefab
wait how
Poor error message but, you're trying to mess with a particle system that isn't really initialized
It doesn't exist in the world
It's just a prefab
one sec
Calling Emit on a prefab is similarly wild
How is this possible?
My array is returning all zeroes, but the static variables are set
but I instantiate the prefab
//gun script
if (GetComponentInChildren<BulletT>(true) == null)
Instantiate(bullet, transform.Find("ShootingSpot"));
//bellow is the bullet script
void Awake()
{
Emitter = GetComponent<ParticleSystem>();
Debug.Log(Emitter);
}
Your code could have changed the values in the array after it was created for example
Would creating a variable reset the static onces?
Not really sure what you mean by that tbh
where is it being reset?
oh wait, I think I know what happened. Thanks @leaden ice
could it be that the static array is initialized before the static variables are?
what does SetHexSize even do?
Doesn't it need to be
[SerializeField]
Class_AB class_ab = new Class_AB();
?
okay, so what are you trying to do with
HexTile hex;
what are you trying to reset?
Im creating a mesh using a group of hex
I created static variables to hold the hex sizes...which are uniform for all hexes
first things first, doing HexTile hex; like that has nothing to do with static variables. That's just creating a local variable of type HexTile
outerRadius is const?
just static
how does it compile even then
so what are you trying to reset?
im initiating static variables from another class
but the array for some reason is not updated
TIL there are no limitations on static fields in initializer
which is very bad and you shouldnt do it
because exactly of your issue the order of init is undefined
so the array is getting init before the variables are then?
This or making the field public.
@rancid frost instead of that just use InitializeOnLoadMethod or RuntimeInitializeOnLoadMethod
if you need the statics
actually not "or" but both for it to work correctly in editor as well, if you need it at edit time
ok, will do
also where do you set the fields?
i dont see it
they are all 0
oh
no that would never work, the initialization happens when static contructor is invoked
so it will happen before you assign any values externally to those fields
thus they are zero
ok
since the array is not a method, i cant use those
you dont use it on array
static class Util
{
public int[] array;
[RuntimeInitializeOnLoadMethod]
static void Init()
{
array = ...
}
}
this at least will ensure that the static constructor is called before everything else
not the first time you access static members of that class
plus not everything is allowed to be called from ctor, so this is a safe init point
ok
Is there a way to edit these values from editor?
I know static variables cant be edited from editor, I thought perhaps making it a singleton
instead of that you should use a scriptable object
which you can then make a singleton if you need
so access would be something like
HexSettings.instance.stepDistance;
Yeah scriptable objects as static variable holders are rly powerfull
Having it as a singleton doesn't make much sense tho'
I mean yeah u can just make it serializeable reference, or find it with resources folder find
Anyway the strength of SO is that u dont have to make new instance/object for it in every scene like you would with monobehaviour singleton
so SO = singleton?
No
SO= Scriptable Object
ignore my brain lagging
But scritpable object can be singleton or not, doesnt rly matter that much, i think singleton is unnecessary, because it only saves the hustle of adding it to every object where u need it in inspector(which i myself avoid with custom attribute fields and other fancy stuff, but lets not go deeper onto that)
I see
so, if I am sure Im only gonna use it once and wont modify, I should go with SO
no
It's not that
SO is simply a serialized class
data object, for configs, definitions etc
it is treated as just another asset on disk in the project that you can edit with inspector
See it as a prefab that just holds your variables
ok
can you create SO simpler than adding definition and menu annotation and click menu -> scriptable object -> create my scriptable object?
Depends on the use case, but you can instantiate it as you would with a prefab
what's the use case for that? doesn't it defeat the purpose of SO?
Tool dev when your SO is a template for some object your tool would generate
At runtime, it's not necessarily interesting
ah, ok
But, imagine you have an item editor to create fancy swords, shields, and so on, it is useful
so that's to generate and save SO dynamically I understand
instead of clicking create and filling out SO properties manually
Do you try to write your scripts so that anything that is possible will work in the editor? E.g. for generating terrain you don't need a game instance and just a custom editor with "Re-generate" button. So that you can fiddle with that instead of hitting "Play" all the time. Is that good or a waste of time?
Yeah, I couldn't exactly remember the syntax and didn't have an IDE at the time. That looks more familiar . . .
Only you can answer that question for your use case
things like these can accelerate content production massively
you just need to weigh cost/benefits
Ok, thanks
Hi everyone, I was wondering if there was a way to do a Physics.CheckSphere, but only for a specific collider?
I know I could just do OverlapSphere and then loop through checking if that sphere was in the list, but that seems inefficient to me given I only want to test against 1 collider rather then many. Is this possible?
You can put the specific collider on a special layer and make your CheckSphere use a layermask
It would be a bit hard to do this given I'm using tags and layers for these spheres already for something else. Is there a way to do this without layers and tags?
colliders* not sphers sorry
you could use methods from the collider its self
Create a script or put some variable on the script that can help you distinguish different gameobjects
colliders have there own ClosestPoint and Raycast methods
that only act on said collider
Does the collider have (is contained within sphere) type methods? I'll look into that. thanks
what type of collider is it?
also you could just say screw it, and do a regular sphere check, and just filter the results based on a component
But I think it doesn't really answer their problem. I think their idea was to ignore all but a specific collider. ComputePenetration would still require to loop through colliders which entered the overlap sphere (from what the example show I mean)
either see if you can do what you want based on the per collider methods
or jsut filter out the results
i dont understand, if you already know the specific collider why loop?
either by holding reference to the good colliders and comparing
or checking for a component
Its meant to be a 3D pickup interactable system for VR, so interactable items sit on a interactable layer (then get shifted to a different layer so they don't interact with the hands for a few frames after release). I'm working on expanding this to two hands to allow for the second hand to look like its changing its anaimation if its attempting interaction and is within range of the given collider. This is more or less done now but right now I'm using a distance check. I want to make this more robust and have it be that if the collider that invokes the interaction is still colliding during a "holding phase" then change animation, rather then just doing it arbitaruly with a distance check (as there could be much larger or smaller objects)
k but what i said would still work
This seems good, can you create colliders as tempuary objects rather then having to use components?
Yeah I think I am just going to do that
regular OverlapSphere, then you check the results contains the collider you care about
Right. But why would the OverlapSphere object hold a ref to the other Collider ?
Collider[] result = UnityEngine.Physics.OverlapSphere(_transform.position + _transform.rotation * _sphereCollisionTestOffset, _sphereCollisionTestRadius, _interactionlayerMask);
return result.Any(resultsCollider => collider.GetInstanceID() == resultsCollider.GetInstanceID());
This is what I think I'll go with for now, just filter the results and see if the spehre I care about is in there. But I am intrested to see if there are better ways of doing this though
since there is already a interactable layer, you are not going to need to loop that much
though i would use the NonAlloc version
why use instanceid
you can just compare the colliders directly
Good point xD
they are reference types and will compare by pointer
Removed the instance ID part now
confused me, initially it was a specific collider test, turned out to be actually finding a specific collider
well its a certain collider he just wants to know if its in a certain radius
Why use physics if it's just a distance test ?
also, if its 1 collider and 1 raidus to check
distance is enough
though guess he wants to account of the size of the collider
If it's a primitive collider, you can access its size and adjust your distance formula without using Physics. It would cost less.
thats assuming its not a mesh or a compound collider
But, I don't know their exact use case, so I'll assume they know what they want
I assume distance check would need to use the closet point on a sphere. Which I can get with the collider, but what would happen with the point is inside the collider?
have done plenty of games with hundreds of raycasts per frame, and perf is fine
would just make it work in the way you best understand and move on to other things to solve
Since they were talking developing for VR, I assumed the less it costs, the better it would be
Yeah probs for the best, I'm jsut just obessing over the performance
we are still talking 2 things of very similar performance, so would go for corectness and ease of understanding above all
And I agree with this statement lmao
perf you learn with experience what to worry about. but generally make it right and easy to understand and only if there is a issue profile and learn why
10 or 12 years ago, i am sure i used to obess over small things like that too, just kinda comes with learning
Hi everyone, I came here with a question, I actually try to make some UnitTest on my unityGame et learn about Assembly, I create a Assembly for test and my principal application and I wanted to create another assembly for my Object models, but I have a problem, in my assembly I linked the Application assembly (the main prog) and the Entities assembly, in my application, nothing change it’s work good, but, I wanted to move my player script in a model and I use some script in my main assembly.
So the question is: did I have a possibility to use some script from the main (if I link the Application assembly to the Entities assembly he gonna make a loop so a new error) or I need to recreate my player object?
i did this
but if I do this in my entities and link the main project ( Application) I get a error because I create a loop
I don't know if this gonna help but i create a schema of my problem
Any idea why invoking UnityEvent doesn't play particle effect? It does invoke other methods correctly and the particle system plays correctly if I press the editor's Play button
I doubt this is possible to do in any easy way but...
Can I somehow get the material ID of where my raycast hits?
idk if this is the right channel for this but I want to make real-time voxel models in my game, so i have instantiated some gameobjects for the general shape of the voxel and i want to 'scan' over these game objects and generate a mesh which converts them to voxel, does anybody know how i can do this?
You should follow a tutorial on how to do it.
There is multiple one out there
you could use hit.GetComponent<MeshRenderer>().material to get the material?
sharedMaterial*
ok i'll have a look thanks
Yeh but there are multiple materials, so it's getting the correct one
Yeh that's not the issue, I was hoping there might be some kind of way of the ray cast telling me what face was hit so I can get the ID from that
But I guess I'm going to have to just have colliders for different material ID segments and pull an ID from that... Not how I'd like to do it but I think that's the only way?
Which you can use with https://docs.unity3d.com/ScriptReference/Mesh.GetSubMesh.html
Hmm that might be the way, thanks
I'll have a look
I see so the Submesh is rendered seperately because of the shader on it, so that'd be my material ID
hello im not sure if this is the right channel but does anyone know why this happens?
so what happens?
It gets locked in an animation
The animator states might not be set right so it's not exiting out of that run animation
Or your code isn't updating it right
#🏃┃animation Might be because of exit time.
i observed that when i disabled the constraint for the freeze rotation option the problem didnt occur
code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private Animator anim;
private SpriteRenderer sprite;
private float dirX = 0;
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody2D>();
sprite = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * 8f, rb.velocity.y);
UpdateAnimationUpdate();
}
private void UpdateAnimationUpdate()
{
if (Input.GetButtonDown("Jump"))
{
rb.velocity = new Vector2(0, 14);
}
if (dirX > 0f)
{
anim.SetBool("running", true);
}
else if (dirX < 0f)
{
anim.SetBool("running", true);
sprite.flipX = true;
}
else
{
anim.SetBool("running", false);
}
}
}
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
So I have been going absolutely crazy trying to find the culprit of this twitch on my player character's left arm. At first I thought this might be an animation problem (the hints and IK controls are the visualized gizmos) but none of them are moving in a way that should cause this. The twist is this only happens in some of my scenes. Does anyone know what I might be missing?
is there a fix the non-uniform parent thing? or do I just have to suffer
rule of thumb: don't do non uniform scaling on any objects that have children
but what if I have to?
Is your object far away from the origin in world space?
you never have to
it seems ineffecient to make a different model for every stretched cube that happens to have children
show me your hierarchy, I'll show you how you can rearrange it
you are doing it wrong
ok ok one second
you are doing this:
Cube (MeshRenderer, scaled)
Child```
You should do this:
Empty Parent
Cube (MeshRenderer, scaled)
Child```
good point
I have tried to do that and Im doing it more
bro at the start of this project I was making all of my mats emissive 💀
is there an existing attribute/easy hack to have a field of a subclass be serialized above the fields of their parent class in the editor?
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Wow, that looks to be the issue somehow.
Try to keep your objects within ~1000 units from the origin
All of my scenes are placed relative to one another, ie a zone in the north will be much further on the Z.
if you have a large world you will need to use a floating origin technique
Otherwise this will be a constant issue
Yeah I've heard of this although I didn't realize how quickly it can become a problem. The issue is happening right around 900 units from the origin. How does it work? I'm curious why the issue is only presenting itself on this one obscure case on the player's idle animation.
that's just hte nature of floating point numbers
the distribution is such that they are much more concentrated around the origin
and it drops off very quickly
half of all possible floating point values are between -1 and 1
float is a 32 bit value so only a finite number of numbers are possible to represent
Yeah that makes sense. I'm just confused why it's only presenting itself on one aspect of the animation and no others.
as you get further from the origin, the distance between these values increases, hence less precision
You can also see it happening to part of the shadow
it's actually also happening in the shadow
under the right chin
I guess those are the ones who can't get an accurate value
The rest probably has some sort of precise value
If you move the character it probably happends to the rest too?
hey, so Im making a game and I need to code so that the camera and the character are 0.266m away from each other so I coded a script that makes the camera always be 0.266 more on the Z axis but now when I look the other way I see my own body
and I did that cuz I want the player to be able to look down and see his legs
can someone suggest something that can make for example the character always teleport 0.266 behind the camera on the Z axis in that rotation, cuz I programmed the character to rotate and move with the camera
@leaden ice @thin aurora I believe that is just the way my toon shader presents itself from the scene camera. I'm not noticing a difference in shadow quality between 0, 0, 0 and 1500, 0, 1500
It seems the only thing behaving differently is that arm
!image
can I post images here?
I am trying to make this game where the distance between your character and the camera is 0.266, the camera is in front of the player and when you look down you see your own body. Everything works well but when you start rotating the character does rotate but since the camera is 0.266m in front of it and you rotate 180° you see your own eyes.
How do I fix this issue I brainstormed of ideas how I can fix this but just can't implement them. I tried making the character basically orbit the camera while rotating and the same with the camera. Can someone please try to help me?
eh just cull the face meshes from the camera
but its also doing it with the legs so if I disable viewing the legs I wont see them in the front and I want to see them
your head shouldn't even be able to rotate past the shoulders anyway
if you rotate past that your body would turn
yea but I just made code that rotates the camera anywhere while moving the character with it
would you be able to vc cuz its hard to explain by words
negative
time to change it then
do I have to tho
also part of the problem though i bet is near clipping plane
Ive got an array of vector3s where i want voxels to be placed using a custom mesh renderer, does anybody know how i can cycle loops through the positions and create the voxel faces at each one, I can't find a tutorial just for this
Use a for loop
i've got that, im just confused on what all the vertices and tris need to be
Are these animation events bad for performance, since it says they are the same as SendMessage?
Hi, I'm attempting to create a low-poly model of a room and would like to animate each component - the planks, doors, windows, etc., - flying into their correct positions. I've considered using a shader and vertex color but would prefer a method that offers more control. Does anyone have suggestions on the easiest way to achieve this?
Animate in what way ?
Yes and no. They are definitely not performant, however it should not cause an issue.
Like every element fly in
got it, thanks
Finally two animation, first when room appears, and then element fly out when before I remove room
Just use an animator if it is always the same motion or use code otherwise.
Definitly not shader
But it's ok if you have a lot separate meshes instead of one
Because I have to have all elements separately
To animate every planks etc
Yes, you can as many as you want item.
Ok so other question, I imported model from blender and Its automaticly created a prefab with all meshes, and right no I want add script to this prefab end get all children meshes how I can hande it?
pull the prefab into the scene
right click it -> Prefab -> Unpack Prefab Completely
Do whatever you want with it
Save as a new prefab by dragging the object into your project window/assets folder
Hello, i made a ScriptableObject for creating quests. But the problem is when i start the scene some values are going default every time here is the before start and after start
Just three of them going default
you'd have to show code
the instance ID of the second object shows that it was created at runtime
the first one is an asset
Ah so
I need to make an init
for it
Thank you! I will do it. Probably %99 will be done
System.Serializable is not needed for a ScriptableObject
I need some help with rotations. I need to calculate the difrence between 2 objects and apply it to a third one but i get a difrent rotation everytime and i couldnt find a solution online.
Quaternion diff = toObject.rotation * Quaternion.Inverse(fromObject.rotation);
affectedObject.rotation *= diff;```
should be that
thank you, that worked
hey im having issues with a model i rigged with maximo does anyone reconize the issue?
not a code question
Sorry
okay, so my friend followed some of sebastian langue's prod landmass generation and we're not done with the series yet and ours is slightly different than his but not too different, but our issue anyways is that our chunks are inconsistent and dont offset correctly as shown here, only some of them are connecting fine but very few only
i dont know which part of the code would affect this, i do know the codebase because i learned it a bit as well but i don't know where to look for this
we got past threading to the "seams" episode
Is it important to keep namespaces? Rider constantly puts them in for me but I don't feel a need for them
Namespaces are good for organizing your code. If you don't feel they're helping you, you don't need them
they are an organizational tool only
they also let you use the same class name twice (by having it in different namespaces)
Its a good habit to be in, I believe the compiler can produce a better result if you setup namespaces for it correctly
I want to say in some way or another your compile time improves, because without namespaces the compiler basically has to search your entire project for everything, whereas namespaces substantially reduce its search space for <thing>
I usually divide my enums out via namespaces
I think also it helps with recompiling, because the compiler can check if a given namespace is "dirty" and determine if it needs recompiling?
Like if you have files in NamespaceA and NamespaceB, and you make changes to a file in NamespaceB, it will only recompile the stuff for NamespaceB, because it can tell that nothing changed over in A.,.. I think
compilers are like 95% ancient black magicks so, its prolly 1000x more complicated than that
Does anyone know the difference between declaring a two dimensional array like this: int[,] array; or like this: int[][] array; ? Is the difference just that with the second option you can have different length arrays in the second dimension?
exactly, the first one is always a "Rectangle" so to say
Ok, cool. I just found out about the second option. Using a list of arrays is annoying to get different length ones, this is much better
Depending on the purpose of the object, you may also wanna consider a Hashset<Vector2> or etc
It's arrays of indexes, so I think this one makes more sense
For the state of user choices in different parts of my menu, so when they come back to it the same choice is still selected
Hey all, I was wondering if any of you have worked with WebCamTextures before. I am trying to get the webcam into a 48x48 Color32[], and figured a good way to do that would be to read the WebCamTexture in as a 48x48 texture. However, after calling webcamTexture.Play() it seems to immediately change the texture back to 1920x1080. If I don't call webcamTexture.Play(), it seems to be stuck at 16x16, I have no idea where it's getting that from. Any help is MASSIVELY appreciated!
Do you mean always a "square" in the first one? Otherwise, I'm now confused about the difference. I thought the SECOND one had different lengths (thus, a rectangle) but the first has the same lengths (thus, a square)
{
currentWeaponIndex += (int)Input.GetAxis("Mouse ScrollWheel");
weapon.currentWeaponData = weapons[currentWeaponIndex];
if (currentWeaponIndex < 0)
currentWeaponIndex = weapons.Count - 1;
if (currentWeaponIndex > weapons.Count - 1)
currentWeaponIndex = 0;
}``` for some reason the variable "currentWeaponIndex" isn't looping, does anyone know why?
In case anyone comes across a similar problem, I am possibly making some headway with Graphics.Blit()
Make sure nothing is setting them?
I recommend ctrl+shift+f and find all instances of that variable. (Or ctrl+t for symbol search)
if oyu're on Windows, Input.GetAxis("Mouse ScrollWheel"); is going to return values like -120, 120
you're also doing weapon.currentWeaponData = weapons[currentWeaponIndex]; before you wrap the index
so you'll end up getting an error before it happens (and also stopping the wrapping code from running)
wrap the index?
The two if statements. Wrap the value around for it to not get out of bounds
But yeah and the 120, -120 will actually depend on your Windows settings, you're better off checking if the value is positive or negative and adding/subtracting 1 accordingly
Ahh yeah I see it now
ty it works now
Can anyone point me towards a solution for using the New Unity Input System across multiple scenes as it's not possible (or I do not know how) to assign functions and objects from other scenes to be triggered by key presses? Thanks
The input system is really not relevant to the question. You're basically just asking at this point how to have objects reference objects from other scenes
and there are tons of ways to do that, such as:
- using singletons
- using opportunistic assignment (assigning references when instantiating things, or colliding with things)
- using Find-style functions like FindWithTag
with the input system in the mix it would just involve either your scripts getting references to the input system constructs, or the scripts that handle input getting references to the other scripts to do stuff. Either way can work
I can do that part, my issue is assigning an object + contained function to an actionEvent in the New Input System at runtime (not even sure if doable).
InputActions have events for performed, started, canceled and you can subscribe to those at runtime
they are normal C# events
that is one possible way to do it
Oh okay, will read into that, thanks.
Do you happen to know how to access them?
Or could point me towards the right doc
inputActions.yourActionName.performed += ...
idk what actionEvents is really
that's not what you need
depending on what _playerInput is, will determine the answer
It's a default New Input System thing (afaik)
if it's an instance of the built in PlayerInput component, you'd do something like _playerInput.actions["MapName/ActionName"].performed += MyFunction;
Okay so that doesn't require you to subscribe to events from your own script
That's it I think
you could also just assign the unity event to a function on the object itself, and then delegate from there however you wish in code
either with your own event, or... whatever else you want to do
This component does it for you, and you have some options to have the events relayed to you
That's how I decided to handle multiple scenes, could be not the best way to go about it but that's what I got so far
interesting
It's one of the few ways to receive input. You could also tick "Generate C# class" on your input actions asset, and then create a new instance of it here and there, on each script that needs to receive input
Even in multiple scenes
On multiple objects at once
note then that those instances will be separate
hmm, so does the function have to be something special?
which might be ok for you and might not
it needs to follow the delegate type
first off that's not how you subscribe
you don't call it
get rid of the ()
Ah and method needs callbackcontext, i see
second - it has to match the delegate type:
Action<InputAction.CallbackContext>```
yes
it needs that InputAction.CallbackContext parameter
and to return void
in inspector, i have a small silly button to generate nodes called Create
what this does is call Create on a class Navmesh
Create goes through all objects in the scene (this is gonna be changed since its slow and kinda pointless, but it works for now), and creates a node for each vertices each object has
Nodes are valid, their positions and everything.
However, in the following code:
public void OnDrawGizmos() {
foreach (Node node in Nodes) {
foreach (Node connection in node) {
Gizmos.DrawLine(node.position + Vector3.up, connection.position + Vector3.up);
}
}
}```
The lines only appear for a frame (unless the scene view is frozen, such as doing something outside of the scene view, but still a frame technically), why is that? They also don't re-appear, even though ``Nodes`` doesn't get cleared or anything
I have a camera controller which is supposed to follow the player. It subscribes to the player spawner to start following after the player is spawned. However the player spawner happens to work before the camera controller (both things happen in awake). How would you solve such a problem?
@leaden ice @simple egret any idea what could wrong here?
what is line 21
If the string is wrong it will give a different error so "Game/Toggle Console" is correct
It's the line shown above in the screenshot
_playerInput.actions["Game/Toggle Console"].performed += GameServices.ConsoleKeyInputsTemp.InputToggleConsole;
what is GameServices.ConsoleKeyInputsTemp.InputToggleConsole?
and GameServices.ConsoleKeyInputsTemp?
so - are you sure that's not null?
Yeah it's probably null
it's not getting assigned until Start
And you're doing this subscription in Awake
you should reverse it
That GameManager thing should be Awake
and the subscription should happen in Start
how could I reference the player rigidbody to the grenade? i want to add the velocity of the player to the velocity of the grenade gameobject
I would just do this in the script presumably on the player that throws the grenade
how would you do that
have it directly reference the player's RB
and add the velocity when throwing the grenade
how might i have it directly reference it and get that information to the script
the same way you did it in the grenade script
make a public field
drag and drop it in
@leaden ice that was indeed it (plus other extra me errors), tyvm, i'm now able to reproduce it for other actions/scenes!
I would do it something like this:
public Rigidbody playerBody; // drag and drop
public Grenade grenadePrefab; // drag and drop the prefab here
void ThrowGrenade() {
Grenade newGrenade = Instantiate(grenadePrefab);
newGrenade.Throw(playerBody.velocity + whateverOtherVelocityYouWant);
}``` @hidden flicker
ok thank you
I have an interface that is only implemented on MonoBehaviours. If I make a variable of type interface, it doesn't serialize in the inspector, I think because it doesn't know it's a UnityEngine Object. I can't System.Serializable an interface either. Is there a way I can drag in a MonoBehaviour implementing an interface into a variable of that interface's type?
Is there a best practice for determining if a Rigidbody (not Rigidbody2D) is grounded? I'm working on a hierarchal state machine w/ a grounded super-state.
Using SerializeReference on the field I believe
Hm, it shows up in the inspector now, but there's no box to drag in
U cant serialize interface iirc
Ok double update: I actually don't know if I've made progress. The rendertexture seems to not actually take on the values assigned to it
Is there a simple way to use lighting settings from an additive scene, loaded at runtime?
(instead of settings from the scene used to load the additive scene which happens by default)
would anyone know anything about this
Unity uses the lighting settings from whatever the "active" scene is currently
I'm trying to get the grenade to invoke the explode method in the explosion script, but i'm getting the "object reference not set to instance of an object" error.
sounds like you didn't assign explosion in the inspector
What line gives that error(it reads on the log and also u should be able to double click it to open right that line)
16, grenade
Your ss doesnt show lines ;-;
the prefab has the script, though.
it's the one with invoke
oops lmao
and this is the reason for the error
Yeah, sounds like it
the grenade prefab has the explosion script
but you didn't assign the field
Show inspector of grenade
this looks like a totally different script
where's the Grenade script here?
at the top
as per this screenshot there should be an explosion field on it
No that has just capsule collider, rigidbody, and explosion
theere we go
the fields in your inspector aren't matching the ones in your script. That means you have two different scripts or you haven't saved your code
solved it. the reference to the explosion script said explosion, so i thought it had autoreferenced
it had not
Autoreferencing isnt a thing in unity
||😭😭||
i mean i think it's done it before???
thanks, exactly what i was looking for
:(
I'm working with a hierarchal state machine, and in my grounded super-state (currently my only existing state), for some reason, my character's rigidbody just won't move. The following is my code in FixedUpdate().
//Vector3 moveDirection = new Vector3(move.x, 0, move.y);
//moveDirection = _sc.Player.transform.TransformDirection(moveDirection);
//moveDirection *= _sc.Speed;
_sc.PlayerRB.MovePosition(new Vector3(move.x, 0, move.y));
MovePosition takes in an absolute position. It's not relative
at the very least I would expect _sc.PlayerRB.MovePosition(_sc.PlayerRB.position + new Vector3(move.x, 0, move.y));
Also why are you calculating this moveDirection variable and then ignoring it?
Sorry, let me provide more context:
There is an InputManager script that manages all the inputs. The movement input is read as a Vector2. move is a reference to the movement input being read as a Vector2 (this reference is not in the FixedUpdate()). I should have commented out a certain part of the code before sending.
I thought that much was obvious
my comments still stand
move = _sc.PlayerInputManager.imMovementInput;
^^^ This is being set in OnEnter().
none of that changes what I wrote. It reinforces it actually
