#archived-code-advanced
1 messages · Page 5 of 1
html is not a programming language and python barely so
These tutorials are especially nice because you can try out the code in the browser directly
I know the MERE basics of C#, like how to declare a variable, how to write “Hello World” etc
It’s just that I’m a games development student, and I’m trying to learn C# because the software at where I am is a bit naff (Heard of Construct 2?) - as well as learning no programming
start with thinking in python and just looking up the c# syntax for that, they're both general programming languages and pretty easy to transition to
then look at the MS stuff, it' can't hurt
And I wanna start using Unity to up my game in games development.
Better to be proficient in C# before tackling Unity than to try to do both at once
Are there any programming languages that are similar to C#?
Beef
what?
Its the other way around. Java is super similar to C#. C# has almost no resemblance of Javascript.
ok i was able to find the visual studio editor but it still fails
what, I can convert c# to javascript in a matter of seconds
So would it be ideal to learn Java, before learning C#?
Why take the step in-between? Just learn C#
Yes, I think starting with C# is okay. When you get comfortable with writing code, testing and design you can pick up Unity for extra challenge.
What? Its -dynamically typed -interpeted -weakly typed
Half of the C# primitives don't exist in JS. 
The syntax is completly different. With most keywords also being different.
just learn C#
I posted in code general im coming to here now
how come enabling a box collider from a script isnt triggering an OnTriggerEnter2D event?
it just doesn't work that way
unfortunately
how would i make this work this way
is there a workaround
i mean i know a workaround but im looking to see why this doesnt work first
that's how unity is made
because technically the thing doesn't enter it when activated
:(
Hi. I have a screen space ui. I have a script that works perfectly where I put a UI square on top of the target (first person camera). I want the square to stay in the screen (on the border) when the target leaves the viewport so the player knows where to turn
Any idea how to do this? I’ve tried way too many things. I can already remove it when it is facing the back of the camera but there’s an angle where the world space conversions start giving crazy values
sound slike my problem. but i want my target icon to stay inside a circle.
Question guys and gals:
I have ascript that almost works. but i need your help to solve the issue.
Im targeting a 3D object thru a worldtoscreenpoint and showing it on a canvas UI.
that works. but i want to clamp the border in a circle, so the target icon doesnt go outside the circle, but still tracks the target.
here is the code. i need the last part to work with the following bit to work together.
Using the clampMagnitude with the anchorPos.
Right now, it just places the icon on top of the camera 0,0,0 position. And doesnt move.
here is the code:
//2D Icon following a 3D object on a canvas.
rawImage.texture = reticle;
targetXY = thisCam.WorldToScreenPoint(target.transform.position);
Vector2 anchoredPos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(parent, targetXY, thisCam, out anchoredPos);
//Clamping the Icon inside this radius. How can this work with following the 3D object so its clamped but still move towards the object?
image.anchoredPosition = anchoredPos;
var positionXY = new Vector2(anchoredPos.x, anchoredPos.y);
positionXY = Vector2.ClampMagnitude(positionXY, boundryRadius);
//Positioning the Icon to match the canvas and the 3D object.
image.anchoredPosition = anchoredPos;
im super greatful for all help.
how to i get the device and and ad id? And directly from within the editor or even android studio for easy copy pasting?
is this a code related problem?
advanced problem
it's a code related channel
these channels are usually for anything generally related to unity. besides most of unity stuff is totally in the editor, so it's understood that non-code related questions are allowed
"Ask questions and discuss anything related to advanced coding concepts in Unity"
I don't see how is this related to advanced coding
code channels are for code problems
how do I get the ad id from the editor?
I have no idea. Ask in a proper channel #🔎┃find-a-channel
wondering, if i alocate more memory than i need for something with Marshal.AllocHGlobal() will this cause issues or will it just be inefficient?
ok it appears that it doesn't mind,
Anyone know why Plastic SCM constantly adds files to the Pending Changes list that haven't actually been changed...and how to stop it from doing that?
building linux il2cpp player requires a linux sysroot package to be installed.
LinuxBuild support both mono and IL2CPP is installed.
Unity version 2021.2.19f1 M1 Chip
Could anyone help with this?
Does C# still not support operator overloading using extension methods?
since when they changed that anyway 🧐
I don't think so
Be happy, you should respect C#, if you have coded Java. Java does not have operator overloading at all
🤣
how would i access a rendertarget of a render texture or really of anything that has one in unity? (i know it is possible according to the unity docs, it just doesn't really explain how)
Hello, I am fairly new to Unity 3d. So, I've been trying to make a FPS game in unity using raycasts for a college project. I've used the shooting code from Brackey's YT tutorial (I think so, I copied the code ages ago). Shooting seems to work on simple 3d objects like a cube but when I apply the "Target" component to a whole enemy AI character, nothing happens. If someone is willing to help me, I would more than love to explain more on the issue through dms!
I wrote this in advanced since Raycasts sound complicated 
You should explain outside of dms in #💻┃code-beginner so everyone who can help has the chance without the need for one person clto commit to it
Okayy I will then
perhaps using https://docs.unity3d.com/ScriptReference/Graphics.SetRenderTarget.html , although i need to get a render target, rather than setting one... Unless perhaps i have to first set one to then get it?
it would be nice if i could just get a list of all render targets but it seems no one in the direct x discord group knows of a way to do that
Hello, is it possible at all to have the mouse cursor appear on a completely different camera?
The mouse cursor appears on the screen, not on any camera
ok...hmm
what I'm trying to do tho is control a cursor or the cursor on a canvas displayed on a different camera
as in a cursor within the monitor
so use a UI Image as a virtual cursor and move that around
ye but new input system go brrrr
input system is irrelevant to the question you asked
Although it might make things easy for you to use that virtual cursor as an actual pointer using https://docs.unity3d.com/Packages/com.unity.inputsystem@1.4/manual/OnScreen.html
cheers
this looks nice
doesn't graphic raycaster still work through the second camera?
you can use the event system to find the position of the pointer in that camera
I have no idea lol very new to all this stuff ngl
however we found out that we can straight up interact with the hidden menu but its completely misaligned but doesnt move around if we move either A) the cam or B) the canvas itself
all I know is I've tried getting the mouse world position and the new input system forces me to use their system but I dont know exactly how to use theirs
hidden menu?
yeah so how it currently works is a main camera looking at the tv
whilst a separate camera is viewing the menu from somewhere else and using a render texture for the tv
try messing with the camera field on the graphic raycaster on the canvas
attached to that secondary camera
yeah
i hear you
try setting the camera field in the graphic raycaster to the secondary camera
using UnityEngine;
using System;
public class FixedCallbackManager : Singleton<FixedCallbackManager>
{
//public Callback physicsSync;
public Callback spawn;
public void Update()
{
spawn.Update();
}
[System.Serializable] public class Callback
{
public float deltaTime;
private float time;
public void Update()
{
if (deltaTime < 0.001) deltaTime = 1;
time += Time.deltaTime;
while(time > deltaTime)
{
time -= deltaTime;
callback();
}
}
public Action callback;
}
}
I keep getting this error and I don't know why
NullReferenceException: Object reference not set to an instance of an object
FixedCallbackManager+Callback.Update () (at Assets/TL-XRI/Managers/FixedCallbackManager.cs:24)
FixedCallbackManager.Update () (at Assets/TL-XRI/Managers/FixedCallbackManager.cs:11)
what is this trying to do
what is your goal?
something akin to a seperate fixed update function
is it supposed to interact with things in the scene?
So I could have multiple fixed updates running at different speeds
I would subscribe other methods to it
how do you imagine the speeds will work? in integer multiples (or fractions) of a frame?
floats for time in between
so for example, 2x a frame, 1x a frame, once every 2 frames..
do you think that's possible?
or what the meaning of that would be?
what is the gameplay objective?
i am suggesting your ead that blog post because, probably your idea of how time and pacing works in unity is wrong
would you like ot learn how it really works?
it would be helpful to know what hte gameplay objective is
The only problem I'm having is not being able to call an Action
trust me that's not the problem you're having
i know a lot more about this than you
what is your gameplay objective?
seperate update loops running at various intervals, to save on performance, because they do not need to be ran every frame, or even every fixed fram
okay, can you give an example?
for example, are you trying to improve rendering performance, or something in your game logic that is expensive to compute?
an example could be pathfinding
okay
or a global spawn method that is synced between multiple spawners
this doesn't sound expesnive
pathfinding does, but also, it usually is not
or a global spawn method that is synced between multiple spawners
this doesn't sound like it has anything to do with trying to make your own player loop. that's the name of the thing you are trying to do, but currently incorrectly, but it would be the wrong thing to use anyway.
I know
you can learn unirx, then this can be as simple as
honsetly, the I'm facing, is that I get an error whenever I try to call an action, regardless of whether there is anything subscribed to it or not
int period = 5;
void Start() {
Observable.EveryUpdate()
// this is monotonic
.Where(_ => Time.frameCount % period == 0)
.Subscribe(_ => {
// whatever you want to execute every period frames, e.g. every 5 frames
})
.AddTo(this);
}
this will be much more valuable to learn
because this obviates the entire thing you're trying to build
if you knew what unirx was
where do I find the graphic raycaster?
calling actions correctly is already figured out by unirx
or you can do something like
void Start() {
SpawnManager.instance.SpawnedAsObservable()
.Subscribe(spawnData => {
// do something whenever the spawn manager spawns a unit
})
.AddTo(this);
}
in other scripts
very succinct, simple, elegant, it already has the "callback" thing you are imagining - that's what a subscribe is.
@ebon fog does that make sense?
caughtchya!
do you have a graphic raycaster ont he secondary camera?
if not, add one
now you can send event system events to its screen space canvas
oh damn is it a component that I need to add then?
ohhhhhh
you definitely have a graphic raycaster on your main camera's canvas
look carefully
i mean, not definitely, but probably - if UGUI has been working, you have one
whaddya think?
or are you just getting mad
even though like 90% of the code in the snippet you posted doesn't make sense
using System;
public class FixedCallbackManager : Singleton<FixedCallbackManager>
{
//public Callback physicsSync;
public Callback spawn;
public void Update()
{
spawn.Update();
}
[System.Serializable] public class Callback
{
public float deltaTime;
private float time;
public void Update()
{
if (deltaTime < 0.001) deltaTime = 1;
time += Time.deltaTime;
while(time > deltaTime)
{
time -= deltaTime;
callback();
}
}
public Action callback;
}
}``` Reposting this for @ebon fog since I'm curious.
Which lines are 11 and 24?
I had to go for supper
11 is in the update monobehaviours update function, 24 is the last line in the while loop
using UnityEngine;
using System;
public class FixedCallbackManager : Singleton<FixedCallbackManager>
{
//public Callback physicsSync;
public Callback spawn;
public void Update()
{
spawn.Update();
}
[System.Serializable] public class Callback
{
public float deltaTime;
private float time;
public void Update()
{
if (deltaTime < 0.001) deltaTime = 1;
time += Time.deltaTime;
while(time > deltaTime)
{
time -= deltaTime;
callback(); //error is here
}
}
public Action callback;
}
}
Okay, I actually don't see where callback is being set, ever. Is it managed outside this class somewhow?
how do you set it
callback = MethodName.
?
You'd have to have already made the function or method somewhere else.
I want a way to create something similar in function to the RenderPipeline.beginCameraRendering, Is that not an Action?
private void SomeMethod() {
Debug.Log("Do something"):
}
void Start() {
myAction = SomeMethod;
myAction?.Invoke();
}```
can you still add methods to that with += ?
An Action is a method with no parameters. It is in the system namespace, not some unity mumbo jumbo.
No, it's not an event. Use public event Action MyEvent; to make events.
Ahh, yes. Better to learn about observables, events, delegates, etc. without also trying to build a game at the same time.
In this case, Action is the delegate. If you wanted your method (or event, whatever) to take an argument, you would need to use one of the generic forms Action<T>, or for two arguments Action<T,T>, etc.
still getting an error
using UnityEngine;
using System;
public class FixedCallbackManager : Singleton<FixedCallbackManager>
{
//public Callback physicsSync;
public Callback spawn;
public void Update()
{
spawn.Update();
}
[System.Serializable] public class Callback
{
public float deltaTime;
private float time;
public void Update()
{
if (deltaTime < 0.001) deltaTime = 1;
time += Time.deltaTime;
while(time > deltaTime)
{
time -= deltaTime;
callback(); // error is still here
}
}
public event Action callback;
}
}
it has nothing subscribed yet
Yeah, then that will happen. The value of an event is null if nothing subscribes to it.
You can't execute a null method (or list of subscribers in this case).
so how do I stop it when there is nothing subscribed
How much programming experience do you have?
I've only used Unity, but I don't think I'm terrible.
Oh, it's fine!
#archived-code-advanced is not really the place for this though, for next time.
sorry
No problem... let's finish this one.
I didn't want to interrupt the other channels because they were in the middle of something though
So, you have a goal in mind that you want to execute callback(), but don't know if the value might be null, right?
yes
Okay. How, using the computer, can be determine if the value of callback might be null, then?
I didn't expect the callback to be null if nothing is subscribed to it since everything else only stays not null unless you set it null
Same reason why arrays complain when they haven't been instantiated.
Right, because an empty array is still an array, as long as it has been instantiated like int[] ints = new int[0], though I've... never written that out before...
thanks again though
yes
you can reassign to a sum too
action = action + anotherAction
Omi already solved this for me but thank you for trying as well
it's just that events are generally annoying, I prefer just delegates
Not on a delegate? Method groups don't accept + operations. Actions are delegates and not events. Unless I am misunderstanding.
Just as a test...
((Action) ShowQuitModal) + ShowQuitModal will work I'm pretty sure
Well, look at that. Learned somethin'.
I guess that puts the "group" in method group. Thanks!~ @maiden turtle
it forces it to make the first delegate from the method, then the second is implicitly converted as an argument to + operator overload of the delegate type
I don't know what you mean by group in method group
@violet valve
ShowQuitModal, with it's signature in this instance is a "method group" (before being cast to Action). You apparently can't add them to each other, but an Action will take a method group through the + operator. I don't know why they're called "method groups" and not just methods internally.
I think that means an unknown overload of a method. like there could be functions with the same name that take different arguments. hence a group
That makes sense, and why I might have come to discover that term.
and it's a good thing they don't create delegates unless you explicitly assign or cast to a delegate type
delegates are objects, they aren't free
This is interesting, and I might see how I can break from events in some cases. I didn't come here to learn things today, but y'know~
Hi there! I was just wondering, does anyone know what the new Input System package does to the game's performance? My team and I are trying to decide how to approach keybindings. And most of the pros of the Input System that I find online are about how easy it is to use and how it takes a lot of work away from the programmer. But we're a little iffy about just downloading packages into the project without fully understanding what it does to it. Would the game run faster with the new Input System or with a custom keybinding script? Thanks!
What I love about it is that it's non-blocking and uses events, which means that your input detection code doesn't have to run for every frame, but only on demand.
OH so it really only runs when it detects input, instead of checking for input every frame?
If by using your "custom keybinding script", you mean building something relies on the Input class, it'll be inherently worse.
Oh? How so? 
Because Input.GetXX is blocking and lives in the Update loop, which can't be as performant.
It has a massive learning curve.
Hahahaha fair enough
however its really worth
@grizzled sonnet It is. The first time you run through it may take some hours, depending on your deduction skills (and until you realize that it just requires a handler class that satisfies some generated interfaces), but I can whip up an input system in 5 minutes because I know how it works. It's great, but it's not as immediate as tossing code into the Update loops of all your MonoBehaviours, which frankly should never have been how it worked in the first place.
Ic ic ic!! I’m not really afraid of the learning curve tbh. I really just needed some sources to convince my boss to let me use the Input System HAHHAHA
Once you get used to it, it's great!
I will tell your boss that the old system is for sissies.
Half tempted to screenshot this and send it to him 
The old system is not for programmers who can comprehend events and delegates. If you can reliably use the whole C# language, it should be immediately understood why input polling does not need to be run as many times per second as your game generates frames.
Tell them that.
The old system, however, is great if you need the entire input system to be understood by your artists and marketing team if they will be helping create actionable gameplay during crunch time, and you haven't feature-locked your inputs. @grizzled sonnet
Icicicic!! Thank you so much!! I’ll be sure to forward this 
are you using eventsystem?
for your game?
Yeah we are
are you doing raycasts through the mouse position a lot?
like to implement a bunch of gameplay?
Not really?
okay
you're going to wind up using Input. in so few places, that you should use Input System instead
you're already in a really good place
We haven’t implemented gameplay yet. We’re currently focusing on the Options/Settings of the game. And we’re trying to make the part where you can change your keybinding
pretty much everywhere you're doing raycasts on Input.mousePosition you should use eventsystem instead
if that's important to you you should definitely 100% absolutely use input system
you can use an asset to help you with the rebinding UI, these things have traditions and you should just copy what people expect

Icic!!
Thank you!
what kind of game is it?
without any gameplay it's hard to say what you guys know
do you know that there is an event system physics raycaster for 3d objects?
I’m sure someone does, but it’s not me 
okay well that's a good quiz question
to find out what you should do
it really depends on the game though
Either way, the takeaway is that polling routines are bad and by using the new input system, you may or may not make huge gains in terms of performance. It's good to know how it works and not tailor your environment to a low common denominator if it is a commercial product.
New inputsystem is nice, but the workflow is not... Glad we have much freedom to make our own thin wrapper with it compared to the legacy... The person who designed it proly just a coding nerd..
And the documentation leaves a lot to be desired, to put it politely
At least changing input bindings in runtime is a lot easier now 😄
Aside from the differences in design due to it using events, can you give me a quick rundown of the advantages of using the new input system?
The way my player control works is kinda like quake, it generates timestamped commands each frame (they need to be saved & sent during networking anyways to make sure the client and server agree on stuff) so I feel like the polling method is more straightforward. But are there real gains to using the newer system?
#🖱️┃input-system message (about advantages of using the new input system)
thanks
Sounds like it would make axes easier
Right now I have every possible axis defined so that they can be mapped to controls at runtime : S
For my game i am caching assetbundles via UnityWebRequest.LoadFromCacheOrDownload
How can i give a script an assetbundle name and asset name from that bundle, and then instantiate it from the cached bundle?
Ah, i think i get it
If i give it a url thats already downloaded it loads it from the cache?
From there i can just load the asset
Hi guys,
I was wondering if an Action could store multiple variables at once. I.e.
-I have a function that requires: Name,Age,Occupation
-I have 40 clients. I need to run this function in sequences
-Each time it runs this functions many things happen in between so I can't have them run all at once
-Each time an Action finishes it will remove itself from the list then go onto the next one.
-Depending on the occupation, there might be cases where more actions get created in the same category but it will process on a different list.
is this a unity question
you can use addressables to cache assets
you shouldn't try to cache them yourself
caches expire and the content has to be immutable
what do i need to point to to access the TextMeshPro component thats a child of a button? I tried with TextMeshProUGUI and that still doesnt work
yourob.transform.GetChild(indexhere).GetComponent<TextMeshPro>();
i assume they are on same object parent
its ok, i fixed it by just making a public GameObject and dropping the Text(TMP) into it, now ill just access it from there
i did that originally to GET the component but then when i would try to change the text i would get error messages for NullReferences saying that i should use an instance of that component, and other things which i forgot already, but thanks.
you will need a GetComponent<TMP_Text> to access that from your publicGameObject
alright thanks
Why not just make a public TMP_Text and drop your gameobject onto that. Much simpler
because the TMP_Text is generated by a nested for loop (which is used to make a grid of buttons) so that TMP doesnt exist before runtime
ok, good response
if i do this to access TMP what do i need to initialise 'child' as, because if i make it a GameObject then it will give me errors
like it will say "Cannot implicitly convert type TMP to GameObject" which makes sense but i have no idea what i should make child then, if i cant make iot a gameobject.
var parent = new GameObject();
var child = new GameObject();
child.AddComponent<TextMeshPro>();
child.transform.SetParent(parent.transform);
parent.transform.GetChild(0).GetComponent<TextMeshPro>();
Something like this
Using var is a pretty bad idea when you don't know what the type is. Whenever you do GetComponent<x> the type is x
anyway these questions should be in #💻┃code-beginner
I agree. Using var on transform foreach will turn it into object. But for the most part it should be correct.
makes sense
yeah i have something similar to that. Is there any way i can now edit the text?
Assuming the component is not null. you can just set it after getting the component.
(getthecomponenthere).text = "blahblah";
Yes. I dont know how you setup your object but the index and the textmeshpro must be a child of the parent you getting component from.
If youre not sure about the index but know there is only 1 component of this type then use yourOb.transform.GetComponentInChildren<TextMeshPro>()
so the GenController is the parent here
and SpawnedTile is spawned as a child of GenController
yeah and it just spawns a clone of a prefab
How does the original button looks like
as in the prefab?
Yes
The hierarchy.
Show the button child.
Change the last line from GenController.transform into spawnedTile.transform.
same thing happens
Whats the latest code. Also is Text (TMP) has TextMeshPro component.
TextMeshPro textMesh = spawnedTile.transform.GetComponentInChildren<TextMeshPro>();
if (textMesh == null)
{
Debug.Log("nooooooooooo");
}
Try check if it exist.
yeah so it says "nooooooo' but thats because i still need to get another child, because like this we are only in 'Button (clone)", but we need to get into that child as well to access TMP
Using getcomponentinchildren traverse the child.
hmm, but by getting 'spawned child' it should still work...
Are you sure you have added textmeshpro to text (tmp) object?
TextMeshPro textMesh = spawnedTile.transform.GetComponent<TextMeshPro>();
if (textMesh == null)
{
Debug.Log("nooooooooooo");
}
Try check if it exist.
Then perhaps its on the button itself
yeah it says it doesnt exist
ill just reshape the button to not have a child but have the TMP on itself
nvm it cant have more than one graphic so it needs to ahve TMP as a child
I really dont know the setup of your project but you can do
(spawnedTile.transform.GetChild(0).GetComponent<TextMeshPro>() ?? spawnedTile.transform.GetChild(0).gameObject.AddComponent<TextMeshPro>()).text = "blahblah";
It basically just create new textmesh if there isnt one found.
thanks anyway for the help
that wont work because of this:
Edited.
🙏
Im writing all of this in phone so i apologize for the messy code.
yeah, ill try figure it out on my own. i still get the same NullReferencError
lmao
the existing component you want to get is not textmeshpro. But rather textmeshprougui.
Yeah thats why i want to make sure its the right component on the object
Suppose I want to replace a serialize field of a parent field by making the type more specific.
public class A : ScriptableObject
{
[SerializeField] private AParentClass FieldToReplace;
}
public class B : A
{
[SerializeField] private new SubclassOfAParentClass FieldToReplace;
}
Is it possible?
does anyone know how you can change the color of these black bars when using the pixel perfect camera component? i couldn't find any info about it on google
Wouldn't you just have the child have AParentClass and then render whatever you need to? your B class shouldn't be concerned with how to serialize/display it, imho?
I want to somehow enforce B to allow a particular implementation of AParentClass in the inspector
Your example is a little confusing because you're using generic names and not really saying what you're triyng to do.. but.. assuming your AParentClass and SubclassOfAParentClass have adequate editor/inspector integration, you'd just have B have an object of AParentClass
you'd design that logic in SubClassOfAParentClass, not in B
I don't know if this works in unity, I seem to remember walking down this path months ago and then giving up, but.. maybe try using a property that determines the type and gets depending on what it is
Let me replace the generic names with the actual problem I am facing, hopefully that will clear things up.
I have a CombatAction scriptable object that allows the player to do something and change the game to the next AGameState, which is also a scriptable object.
This CombatAction is a scriptable object that takes in an AGameState. I have a particular CombatAction that can should move to a particular AGameState called AttackState. The combat action needs to know it's specifically an AttackState so that it can initialise something for the state to work. So the idea here is that someone using the attack combat action scriptable object can drop drag and drop the attack state into the field.
I could just raise an exception if the given state is not the attack state, but I figured it would be better to add a constraint to the field.
Unless if that's not possible.
What's your prefix A denoting, btw? ie, AGameState? Just "a game state"? if so, don't - just use GameState - is that an enum? some people consider it acceptable to postfix it with a word like Type if the base word is too short - like StateType, then you'd have things like:
public class Player : MonoBehaviour
{
public StateType CurrentState;
public StateType LastState;
}
public enum StateType
{
Attacking,
Resting,
Dead,
}
@calm ocean It doesn't seem like a ScriptableObject is what you want here - is there... data related to the actions that you need? Animations, graphics, textures, sounds, etc? It seems like you're building a FSM with ScriptableObjects which... I suppose that's possible? But I'd do it "by hand" and just use a simple enum if my assumptions are right and that you're just doing a simple-ish finite state machine
I have a scriptable objects game state. It was previously an enum but that got unwieldy
Hm.. so.. best approach for FSM in Unity is a few patterns put together.. A "business logic" POCO (or a MonoBehaviour) that manages the logic for state changes, a enum for the state itself, and scriptable objects that contain the data relevant to the states
I tend to use scriptable objects purely as data containers and don't put any logic in them.. you can, but.. i just don't. 🙂
I guess it depends on the size of the FSM. The issue I have with enum state is that there are a bunch of switch cases scattered throughout the code base, and every time you add a new state, you got to hunt down all the times there are switch cases.
Anyway, that's beside the point, I guess there's no way of limiting the type to a specific implementation of a serialized field in the parent class?
Like, the kind of logic I put in them is super lightweight lookup type stuff -
So.. like I mentioned, I think you should centralize all your state changing logic in a single class to orchestrate it.. it'll do things like return a list of valid states that you could move to, get the current state, even publish events on state change that all your UI could subscribe to if appropriate (and you want to make it a singleton)
Well I got all that except getting a list of valid states one could move to
then the rest of your game just does stuff like
if (StateSingleton.CurrentState == Jumping) // display jumping pose..
StateSingleton.JumpEvent += HandleJumpEvent; // start a jump
HashMap<StateType> validNextStates = StateSingleton.GetValidNextStates();
if (validNextStates.Contains(StateType.Jump)) // jump button is enabled
I dunno - it's not for everyone and it's a little bit more boilerplate work but it makes separation of concerns a bit easier.. nothing in your game except for the state manager singleton has to deal with state - everything else just consumes the state and asks the state manager for info about it. Business logic in one place, race conditions eliminated, etc.
If you start having your game have the state management logic all sprinkled around the game (ie, at the interface layer) then refactoring or changing logic is going to be a real pain
hey,
is there is a performance benefit/disadvantage if I split a function into multiple smaller ones?
for example:
I've noticed that I'm using raycast a lot, and they all look similar to each other, just sometimes reacts differently when it hit an object of layer 2 ,4,8,30 .. etc
example :
original
// all adds up to be about 150 lines
RayCastHit hit;
if (Physics.Raycast(source, forward, out hit, maxRange, ~layers))
{
if(hit.transform.gameObject.layer.value == 2){ // do stuff }
if(hit.transform.gameObject.layer.value == 4){ // do stuff }
if(hit.transform.gameObject.layer.value == 8){ // do stuff }
if(hit.transform.gameObject.layer.value == 30){ // do stuff }
else{ // do stuff }
}
what I'm thinking of is to do something like that.
public RaycastHit StartRaycast(Vector3 source, Vector3 forward, float maxRange, LayerMasks ~layers)
{
RayCastHit hit;
if (Physics.Raycast(source, forward, out hit, maxRange, ~layers)) return hit;
}
public void ifLayer2(){// do stuff}
public void ifLayer4(){// do stuff}
public void ifLayer8(){// do stuff}
public void ifLayer30(){// do stuff}
am I overloading the system or wasting the resources if I split the raycast into separated functions? (that way i could swap any function I want with another without having to re-write the whole raycast instance)
I mean.. yes it does matter if you put code into methods
It's called call overhead
But it's usually not an issue
if the issue you are talking about is 0.0000000000000000000000000001 ms then I'm ok with that.
but Im building this for android devices, and I thought why do i need to rewrite the whole raycast script just to change a small tiny thing ?
unless ofc 0.0000000000000000000000000001 ms issue is a problem to android devices.
you can afford to lose some for readability and maintanability
if you remove an unused and empty Update() method from a random component, you already freed up 20x times the performance you lost
I'll double check the update methods when I start to reoptimize everything, but as far as i know I usually add if(!foo)return; on all update functions
You're only hindering your program more by doing that (if the compiler doesn't save you from yourself here)
Personally I would just make the game, and do a few passes of optimization at the end on the biggest problems the profiler gives me.
That would be more efficient then doing it this way.
but I dont think there is anything we can do about it.
for example in any networked game, you only want the localPlayerObject to respond to your arrow movement, and should not move any other playerObject ... so to avoid this we do something like if(!localPlayer) return under update before checking if the player pressed any arrow key.
hello guys, I have a master script NOT associated with any gameobject in the hierarchy, which contains the classes used in my game. Is there any way I can point a GameObject field inside that script to a prefab?
Ah I see that's different
I thought you meant adding an if statement to an empty update method
planning on doing that too but with optimizing on my mind, meaning to minimize the issue during the optimization process.
You could try removing the script altogether or disabling it when it's not owned by the player
that might sometimes work, but it's more likely that u would still need to call stuff on the local script as well., like animating the Non-localPlayer's the gun shooting
Not really - if there's a script that's not tied to a gameobject then .. for all intents and purposes it doesn't exist, and you can't assign members to it. What are you trying to achieve? How does your script that isn't associated with any gameobject being created? If you're doing it run-time (by instantiating it as a component and assigning it to another gameobject) then you could write an Initialize method that takes a prefab or instance of a prefab and assigns it to a member of the script
https://pastebin.com/umCjq1rz have this code and it says 555 formed a new party with 555 Creating Arena2 Instance with zOffset=250 Teleporting 555 to new instance=Arena2(Clone) with partyId=1 but it doesn't port him.
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 is a nave mesh on the area he is on and the arena
it works fine over a local network, but once it's remote the thing doesn't port him
Hi, when I shoot my projectiles on FIxed Update while the player is moving, what happens is when physics updates, the player has moved from the position where the shot came from (projectile created during FixedUpdate, Physics Update after before render). Because the player can move at very high speeds (1000m/s) this looks very strange . Is there a way to run code immediatly after Unity processes physics?
You'll end up with a serialization error due to conflicting fields (you can do the same thing by naming your field after one of Unity's own internal fields like m_Scene)
The issue sounds like you want polymorphic serialization but Unity's serializer doesn't have support for that
Do you think how city building games or strategy games keep stats/attributes?
A list of generic stats? So all types have the same structure.
or separate classes for each type with specific attributes/fields.
In the first approach, I have to define key/value stats for each instance
In the second approach, I only set values but also, I have to define different stat panel (UI) for each type while in the first approach, there is just one stat panel because it can iterate over the stat list
I get it, On Start doesn't run the frame that the object is created, only in the next frame.
And I was only adding velocity on start, so it was starting to move a frame later
Is there a way to run code immediatly after Unity processes physics?
yes, in Update for example, the transforms will already be after physics have processed
Oh I see, thanks, I will find a way to work around that
Can someone help me calculate what the Big O is for this code?
https://pastebin.com/Uy8pS2Wy
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.
neither advanced nor unity related
greetings praetor, do you have any experience with navmesh Warp?
it really depends. if you're working with a pre-existing game; or, the game logic is coded to maximize performance, add interfaces to add "views" to existing code that will be referenced by your UI elements
for example
interface IHasTooltip {
string name;
string description;
}
can be added to many things - things you can mouse over, things that you can't... etc. etc.
in terms of how they are engineered, strategy / spell-like games, where the players can modify the rules over the time by putting things into play, "contain an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp." https://en.wikipedia.org/wiki/Greenspun's_tenth_rule
sometimes this is done by using a dictionary of enum values ("list of attributes")
that are used as variables
in the more robust world it is coded in a scripting language (like lua) or the game stack looks exactly the same as the program stack (all your rules are in c#)
that is hard
//The second approach (separate UI/presenter class for each type)
public class BuildingTypeAPresenter:IBuildingPresenter{
private BuildingTypeAStatPanel _statPanel;
public void Show(int id){
// find building by id
_statPanel.Render(attributesA); // range, speed
}
}
public class BuildingTypeBPresenter:IBuildingPresenter{
private BuildingTypeBStatPanel _statPanel;
public void Show(int id){
// find building by id
_statPanel.Render(attributesB); // count, ...
}
}
public class BuildingController:MonoBehaviour{
private Dictionary<BuildingType,IBuildingPresenter> _presenters;
public void Show(int id, BuildingType type){
_presenters[type].Show(id);
}
}
In my mind, there are ONLY three ways to handle it.
1- Keep all atributes in one key/value list
2- separate data structure for each type
3- keep all fields in one structure (0 value for none)
Do you think how they have stored these buildings? stats
@undone coral Thanks, you have mentioned the first approach, it is really flexible and can ease when accessing data or showing UI (just one class to present) but I have to define key/value for each building/item in db/scriptableobject instead of only values
Maybe, I can have both worlds.
Define separate classes for each type and also fill stat list inside each type.
public class Building{
protected Dictionary<string,int> _stats; // or enum instead of string
public IReadOnlyDictionary<string,int> Stats => _stats;
}
public class BuildingA:Building{
public int Attribute1Value;
public int Attribute2Value;
public int Attribute3Value;
public BuildingA(){
_stats.Add("Attribute1",Attribute1Value);
_stats.Add("Attribute2",Attribute2Value);
//...
}
I think it depends how variable it will be. I don’t think there’s so much attribute variability in those kinds of games
I would use scriptable objects with each stat as a different attribute
And then create a attribute iterator when you want to show things in the UI (could use reflection or something more static)
In those kinds of games you spend a lot of time tweaking values so making them easier to tweak would be a priority for me
Has anyone ever used the recording/playback function at runtime?
What I'm trying to do is similar to functions like POTG in Overwatch.
I want to save + - n seconds as an video from a specific trigger
The difference with the POTG system is that it needs reverse play (for rewind time directing)
Unity's basic Record package does not seem to be able to runtime.
can someone share a good experience about external package or asset?
you will almost certainly need to build something bespoke
Unity's basic Record package does not seem to be able to runtime. sounds like a bad idea... Any games would not use such method for a replay... at least this simple 2d game did it properly https://www.raywenderlich.com/7728186-creating-a-replay-system-in-unity
I have a problem
in my code
i have this function
in my player target script
and it has an if statement
which never seems to go off
any help would be apreciated
my player target script is:
https://paste-bin.xyz/73442
Player Target Script - pastebin -for Sharing Code and Text.
Player Target Script - pastebin Paste can store text, source code or sensitive data for a set period of time.
Player Target Script - pastebin -for Sharing Code and Text.
my movement script is:
https://paste-bin.xyz/73443
i am refering to line 27
Player Target Script - pastebin -for Sharing Code and Text.
Player Target Script - pastebin Paste can store text, source code or sensitive data for a set period of time.
Player Target Script - pastebin -for Sharing Code and Text.
Movement Script - pastebin -for Sharing Code and Text.
Movement Script - pastebin Paste can store text, source code or sensitive data for a set period of time.
Movement Script - pastebin -for Sharing Code and Text.
I used debug.log and health does decrease and does get below 0 so idk
I would appreciate any help
Player Target Script - pastebin Paste can store text, source code or sensitive data for a set period of time.
Movement Script - pastebin Paste can store text, source code or sensitive data for a set period of time.
Where do you call that function?
TakeDamage
put a debug.log inside TakeDamage before the if, and put it inside the if as well
see if any go off
if none go off, you must be changing your health somewhere else
i call it in my hotbar script
sorry
lemme grab it
here
@turbid tinsel
i have a debug log infront of the if and it works
so idk
this is rlly weird
why don't you do playerTarget.TakeDamage(damage); on line 152? shouldn't change much but it's weird
ah
what?
PlayerTarget inherits from target, yes?
yea?
wtf really
yea
PlayerTarget : NetworkBehaviour
and you call the same function on both
I don't think so
nah my target script is dif
idk then
you put debug log printing what?
o yea
my target script is: https://paste-bin.xyz/73588
the health
yea
it goes below 0
ok and?
and it seems fine
and the if doesnt go off?
Ok and a log inside the if?
nothing
show the code with the logs
double click the if
the if statement isnt going off
debug*
wdym
the debug log in the editor, click it and check where it goes
you said you added logs
yea
let's see where you added logs
and what they printed exactyl
I want to see the code with the logs in it and what the result is in the console, yes
and the code?
i gave all the code above
lemme grab it hold on
my target script is: https://paste-bin.xyz/73588
No, you gave the code without any log statements in it. I want to see what the code looked like when you ran the game and got that log output you just shared
I'm really not sure how to be more clear
i havnt change it tho
PlayerTarget
then how are the Debug.Logs popping up
public void TakeDamage(float amount)
{
health -= amount;
if (health <= 0f)
{
Die();
}
}```
I don't see any log statements here
bc thats the target script
it's PlayerTarget
not the player target script
no, that's playerTarget
I literally just copy and paasted from here https://paste-bin.xyz/73442
for me there are
yea
then send us the new one
its that
yea
here
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class PlayerTarget : NetworkBehaviour
{
[SyncVar]
public float health = 50f;
public GameObject playerModel;
PlayerMovement pm = null;
[SyncVar]
public bool isAlive = true;
private void Start()
{
pm = GetComponent<PlayerMovement>();
}
public void TakeDamage(float amount)
{
health -= amount;
Debug.Log(health + " = Health");
if (health <= 0f)
{
Die();
}
}
[Command]
void Die()
{
isAlive = false;
//gameObject.SetActive(false);
playerModel.SetActive(false);
Debug.Log(gameObject.GetInstanceID().ToString() + " has died!");
pm.GetHealth(isAlive);
}
}
thank you
why didn't you add another log INSIDE the if statement
We are trying to verify that the if statement isn't working. It's incumbent you add a log inside the if statment
Which is a fancy [Command]
which may be part of the problem
change
health -= amount;
Debug.Log(health + " = Health");
if (health <= 0f)
{
Die();
}
to
health -= amount;
Debug.Log(health + " = Health");
if (health <= 0f)
{
Debug.Log(health + " = Inside if Health");
Die();
}
that or [SyncVar] if the if really doesn't go off
My guess is this object doesn't have a proper NetworkIdentity or something like that
although that'd be terrifying
{
Debug.Log("If statement is working!!!");
Die();
}```
just added that
so
why isnt the die thing working then?
So it's an issue with [Command]
thats rlly weird
something like this
it's not that weird
but is this code running on a client
and does the client have authority over the object
basically I believe Command needs to run from whichever host has authority on the object
how do i check
I'd double check all that
hold on
I've never really used Mirror but can't you check all that stuff on the NetworkIdentity? Like who has authority on the object etc
yea
it does have authority
so
idk the problem
would it work if i removed the [Command]
i just want it to show on the other client
will it work properly across the network or whatever? Idk
#archived-networking may be where you want to continue this
What pattern would you guys go with for a 2D game (point and click) sort of like civ but without 3D elements.
Perfect, yes setting only values is easier than adding/removing stats (key + value) and also adding/removing stats is error prone and finally, if I need to add an additional stat or remove it, I should do it for all of them. I know I can implement an editor but agree changing/updating stats when it is a list is harder than the method which defines explicit fields
Also, I think it is similar to your suggestion. Keeping an iterator/list to iterate over all stats
but it depends on game. For example, if there are a bunch of stat modifiers, I think keeping stat list is really an elegant way to handle it. ( e.g. Adding x value to each range stat of a building)
Thanks for the reply. I have a master script in my project folder with a namespace, I reference it from the other scripts by the namespace. I'm trying to assign a prefab to it, instead of doing it, for example, from the player, every time I want to instantiate it, just like you suggested. From what I understand, it's almost impossible to do, though... I might have to reword my game architecture, maybe including this master script in one GameObject in the scene
how to limit air control?
If you have a way to track that you are in the air then it's as simple as multiplying the speed to a fraction of what you want it to be
I have a way to track if I am in the air
Let's say you want the air control to be 50% of grounded speed. Just multiply it by 0.5f.
I have a enum
ok lemme try
I'm surprised there's no information about this, I've seen some games even have textures applied to these bars
something like this
Now you need a way to keep track of what is regular speed, like separate your moveSpeed into 2 fields: moveSpeed & currentMoveSpeed
That way when you are grounded again you can set currentMoveSpeed to moveSpeed
maybe its just detected through a checksum of some sort
what will be the difference between current moveSpeed and moveSpeed?
Hi. Some time ago i stumbled across weird issue with updating gradient editor in custom inspectors. I wasn't able to resolve the issue. So if someone would like to see and maybe help, feel free to check out the thread on unity forum: https://forum.unity.com/threads/gradient-propertyfield-not-updating-in-custom-inspector.1319796/
I don't understand the question. What do you mean by that? moveSpeed will be halved by being divided by 2 in that example.
And I see that you already have a way to track what is your regular speed so you can disregard the example I gave you about "currentMoveSpeed" and etc.
https://gdl.space/fucusoroce.cs I tried your code and I tried also something similar to this idea but it dosen't work
You can even simply it further by just having a airSpeed field instead
but I want my player to keep its momentum
can you fix my code and send me?
I can't fix your code but I can help you get there, line 77 and 78 is wrong. Again, I suggested you use fields such as currentMoveSpeed because I didn't know you already had fields to keep track of the base speed
no I added the currentMoveSpeed after you said(suggested)
Does walking and sprinting work? Do they have different speeds when you try them?
If they do, you can do the same thing for when you are in the air, just use an "airSpeed" variable instead
// Jumping
else if (rb.velocity.y > 0)
{
state = MovementState.jumping;
moveSpeed = airSpeed;
}
That should work, right?
ya
ok
but then your air speed will be the same when you jump while walking and also jump while running
Then the example I gave you first should do the trick, provided you only do it once
Because you run that method every frame, that would keep decreasing your speed by half each time. To circumvent this you can just check if the state is already the one you are going to change to, if it is then you can skip it. An example using a guard clause:
else if (rb.velocity.y > 0)
{
if(state == MovementState.jumping) { return; }
state = MovementState.jumping;
moveSpeed = currentSpeed / 2;
}
Also you should check for air by using a ray cast to check if you are on the ground. Using y will give janky behavior on slopes, when falling, etc
its working thank you bro very cool
you edited it but I did what you said already
using my own tiny brain thing
if you dont have enough velocity your air speed will be very small too thx bro
No probs, glad to help!
this is the code I used, I know it can be shortend but who cares for clean code(everyone does except me)
currentSpeed / 2f; please
im using google admob but when the user earns a reward through watching an ad, i get an error when im trying to reward the user with the reward
{
string type = args.Type;
double amount = args.Amount;
MonoBehaviour.print(
"HandleRewardedAdRewarded event received for "
+ amount.ToString() + " " + type);
if (type == "revive")
{
Level2Referencer.Instance.deathTimerManager.Revive();
Level2Referencer.Instance.manager.Revive();
StatSaveManager.Instance.AdWatched();
StatSaveManager.Instance.Save();
}
}```
the error is: UnityException: get_gameObject can only be called from the main thread.
The error points to this:
{
gameObject.SetActive(false);
}```
this is on android btw
Easiest solution is to put all your code into a list of actions and invoke that from within some game objects update function and delete it from the list.
im not sure how to create a list of actions
could you link me to some documentation about it or something
can i also just set a bool about invoking an action
like: public bool invokeAction = false;
and then in the update:
{
Action();
invokeAction = false;
}```
i think this is what you are talking about right?
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Yes. Sorry.
You should just put the evaluation of the HandleUserEarnedReward args into some method and place it into a List<Action>.
In some monobehaviours update you check if there is anything within that list. If so you invoke it and remove it.
Hi, Im trying to simulate rays of light passing through surfaces. I currently have a working system using raycasts and mesh colliders. However, with curved surfaces, mesh colliders are innaccurate so I want to use equations for curved surfaces (e.g x^2 + y^2 + z = 0). However I have no idea how to calculate the intersect between a curved surface and a 3D line. Another problem is that I want to be able to rotate the surface and move the surface similar to how you can rotate objects using Unity's gizmos, but I have no idea on the maths behind this problem. Does anyone know how to do this / can point me to some resources which I can read up on.
Could you get a good approximation by somehow finding adjacent mesh faces and doing some kind of weighted/interpolated average of the surface normals?
Bumping my problem. So... Im trying to create a recoil system for my FPS game.
I can sway the gun with the mouse, i can apply a kickback to z axis, everything is fine but getting the rotational recoil right. Would appreciate some help!
https://hatebin.com/aqsasflcuv
I have tried using lerp, slerp and even the smoothlerp function i use in my adc sistem
https://i.imgur.com/hZRtgjc.png
Is this normal? I am experiencing this since upgrading to Unity 2021.3.7f1 . Before that the Project was on Version 2020.3.36f1 and nothing unsual was there. This is just Resources.Load. Any Idea from what this could come or how to fix it? Oh and it is on Android
what's wrong with it? "it's not working" is not very helpful debugging information
You are Right
that said, my guess looking at your code is that you're seeing instability in the rotation. Sometimes it just freaks out and rotates weirdly. If that's true, it would be because you're both reading from and writing to the rotation using euler angles. The value that euler angles returns to you is not necessarily stable from frame to frame. It can flip by 360 from one frame to the next (ie 90 => -270)
so if you try to lerp or smoothdamp or w/e on an euler angle that you're not tracking yourself
uhm.. i didnt know that. that helps already
you could get some gnarly results
that indeed happened
one other problem is that my targetWeaponRotation goes all the way to 360,0,0
and doesnt really come back
so its not lerping back to vector3.zero
and what happens is that my gun starts to point at the sky and doesnt come back. that happens very slowly tho
you should either:
- store what you think the euler angles should be in your own variable rather than reading it from the transform and overwrite whatever the transform has every frame
or - do everything in quaternions rather than euler angles
a separate issue is that Vector3.SmoothDamp and Vector3.Lerp is not designed for angles, so they don't wrap around
Slerp?
not really. Vector3.Slerp is treating them as directions, not as euler angles
Quaternion.Slerp is really waht you want
but you need to pass quaternions into it, not euler angles
doing everything in quaternions is really a much better option than dealing with euler angles
like, are you just trying to recoil around one axis? Quaternion.AngleAxis
but taking into consideration that i already have a bunch of vector3, i can just convert that into Quaternion.Euler and then pass it to Quaternion.Slerp?
It's both axis unfortunately
you can, but you have to be calculating the Vector3s in a way that is appropriate for euler angles
ie it has to be treating them as angles, not as points in space or as directions
math, not even once kids
nah im joking. I guess i never really thought of it that way
yeah, unity overloads the Vector3 type to mean a lot of different things. It would be nice if there was a bit of type safety between its actual physical meanings rather than just "oh, a vector is a collection of 3 floats, duh"
ok, just from changing to this newRecoilWeaponRotation = Quaternion.Slerp(newRecoilWeaponRotation, Quaternion.Euler(targetRecoilWeaponRotation), snappiness);
it already comes back, very slowly, but it does
if you dont mind me abusing of your good will sir, next step for me would be getting this recoil angle and applying to the raycast
but if i just do (origin - destination) + angle . normalized it gives me very weird results
like not even close to the direction it should be facing
kind of a side note, but this is using lerp "wrong": https://medium.com/swlh/youre-using-lerp-wrong-73579052a3c3
Quaternion.RotateTowards might be more appropriate for this use. But if you already know about that and are consciously doing it because its good enough, carry on.
sorry, I don't see a raycast in the code you linked
trying to wrap my head around what you're asking
you have a raycast for where the gun would fire if unrotated, and you want to apply the rotation to that direction?
yes
public void FireFullAuto()
{
if (bullets > 0 && canShoot)
{
if (Time.time > lastShotTime + fireRate)
{
IncreaseRecoil();
bullets--;
lastShotTime = Time.time;
muzzleFlash.Play();
RaycastHit hit;
if (Physics.Raycast(cameraTransform.position, cameraTransform.forward, out hit, Mathf.Infinity))
{
Vector3 direction = ((hit.point - weaponPivot.GetChild(0).transform.position) + newRecoilWeaponRotation.eulerAngles).normalized;
if (Physics.Raycast(weaponPivot.GetChild(0).transform.position, direction, out hit, Mathf.Infinity))
{
GameObject go = Instantiate(currentGun.bulletHolePrefab, hit.point, Quaternion.LookRotation(hit.normal));
go.transform.position += hit.normal / 1000;
if (hit.transform.CompareTag("Enemy"))
{
Debug.Log("hit enemy");
}
}
}
}
}
else StartCoroutine(Reload(reloadTime));
rotatedVector = quaterion * unrotatedVector
direction + eulerAngles is the same kind of nonsense I was talking about before, mixing up two different meanings of Vector3
"up" as a direction is (0, 1, 0), but up as eulerAngles is like (90, 0, 0). Adding those two things together gives you (90, 1, 0), which is.... very much not the value you were probably looking for
i see
changed it to Vector3 direction = newRecoilWeaponRotation * (hit.point - weaponPivot.GetChild(0).transform.position).normalized;
and it has a pretty decent result to be honest
yep, this looks about right
alright sir, you've given me a better lesson in 10 minutes than many hours of classes in college
thank you so much. i'll make sure to treat my vector3s better after this
you're welcome! glad to help
this conversation got me thinking about whether I can implement a wrapper for them myself so you actually get type safety
that would indeed be very useful
<rant>I hate Quaternions...</rant>
@fringe root Unsolicited opinion - your code would be a lot cleaner if you strived to adopt the "no else" and "only one indent" approach from object calisthenics. Because I'm a terrible person, I refactored your code to show what it might look like. https://pastebin.com/tCKLGYZZ
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.
Quaternion.RotateTowards(_baseRotation, wantedRotation, maxAngle) => if maxAngle = 0, shouldn't this return _baseRotation ?
(i didn't analyize the two-raycast-check thing, i don't quite know what it does, i just reformatted the code a tiny bit)
I don't think so - i think you can have a different quat for the same base rotation, but i honestly don't know, that stuff is like black magic
(think of the case where you are aimed in the same direction but doing a barrel roll)
It currentlies go completely crazy (target is the result of that expression): Base: (0.00, 0.00, 0.00) | Wanted: (359.88, 0.12, 89.96) | Target: (359.99, 0.04, 20.00)
and each frame is different
This moved by 20 degrees, so it basically ignored my max angle
what are you using to get your quats for Quaternion.RotateTowards?
Quaternion wantedRotation = Quaternion.LookRotation(rotatingTransform.InverseTransformDirection((targetPosition - rotatingTransform.position).normalized), rotatingTransform.up);
and _baserotation?
it's localRotation at Start, so 0,0,0
hm, weird.. probably shouldn't matter honestly if the 3rd parameter is 0
maybe there's undocumented/unpredictable behaviour if the parameter is 0.. try setting it to something small like 1
(i believe that's degrees per second, but i forget if it's in degrees or radians or whatever)
degrees
It should be degrees at least according to the example in the documentation
I think I’ve done something similar in the past, I guess I’ll search for it
Quaternions never work 😂
@fringe rootthats one hell of a ladder
How do I clamp a rotation to a given amount? I don’t want my transform to rotate more than X degrees (local rotation)
first get the local rotation of the transform
then call the clamp function and set axis float value to the clamped value
now set the new rotation with the new clamped value
There is no clamp function for quaternions
no but you can get the individual values still and clamp those
drive your rotation from a float
float rotation = 0;
void AddRotation(float amount) {
rotation += amount;
rotation = Mathf.Clamp(amount, min, max);
transform.localRotation = Quaternion.Euler(rotation, 0, 0);
}```
This way is ideal because you don't need to deal with reading euler angles from the Transform, which are very finicky and sometimes give you the negative version etc.
i love it! Will search object calisthenics and try to adopt it more often! ty!
its also called guard clause
Also just realized how dumb it was to have two identical functions called FireSingle and FireFullAuto, when they are already called in diferent conditions
🤦♂️
I installed the Navigation 1.0.0-exp.4 package which includes the NavMeshSurface component, but I can't create a variable in a script to store the component. Any ideas as to why?
I did include UnityEngine.AI
using UnityEngine.AI.Navigation;
There seems to be nothing UnityEngine.AI can derive to
These are all the classes it gives me, and I think NavMeshLink is part of the Navigation package so, I guess the package has been imported
That was it! Thank you very much
having trouble debugging from vscode
gave me this error```[Window Title]
Visual Studio Code
[Content]
error while processing request 'launch' (exception: Object reference not set to an instance of an object. at UnityDebug.UnityDebugSession.CleanPath(String pathToEditorInstanceJson) in D:\prog\external\vscode-unity-debug\UnityDebug\UnityDebugSession.cs:line 339
at UnityDebug.UnityDebugSession.Attach(Response response, Object args) in D:\prog\external\vscode-unity-debug\UnityDebug\UnityDebugSession.cs:line 310
at CallSite.Target(Closure , CallSite , UnityDebugSession , Response , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at UnityDebug.UnityDebugSession.Launch(Response response, Object args) in D:\prog\external\vscode-unity-debug\UnityDebug\UnityDebugSession.cs:line 257
at CallSite.Target(Closure , CallSite , DebugSession , Response , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at VSCodeDebug.DebugSession.DispatchRequest(String command, Object args, Response response) in D:\prog\external\vscode-unity-debug\MonoDebug\src\DebugSession.cs:line 401)
[Open 'launch.json'] [Cancel]```
My use case is basically, I want a turrent to be able to rotate towards a target but it has limits to how much it can rotate (so it has like a firing arc)
_targetRotation = wantedRotation;
rotatingTransform.rotation *= _targetRotation;```
now, I want to make sure the rotatingTransform.localrotation is not above a max angle or else turrets would be super janky (like rotating inwards to the player)
I can't seem to find a way
private Quaternion ClampRotation(Quaternion rotation, float maxAngle)
{
Vector3 angles = rotation.eulerAngles;
angles.x = ClampAngle(angles.x, maxAngle);
angles.y = ClampAngle(angles.y, maxAngle);
angles.z = 0;
return Quaternion.Euler(angles);
}
private float ClampAngle(float angle, float max)
{
if (angle < 180f)
{
return Mathf.Clamp(angle, 0f, max);
}
else
{
return Mathf.Clamp(angle, 360f - max, 360);
}
}```
I tried this but it starts randomly rotating
I just found out in previous projects i basically used IK components but seems like an overkill in this situation
This seems like a pretty standard use case, I don't understand why it is so difficult lol
there are right words for all this stuff and hardly anyone understands them
i read what you are trying to do and it didn't make sense to me
it's difficult to express in words what your hierarchy should be
and then reading this stuff it's tough because you don't use var
it gets really verbose
so it's a code style thing too
you should never ask the turret to rotate to an invalid target rotation
I want to rotate this turret towards a target position. But as you can see in the image, the turret can't rotate X more than 90 degrees or else it will hit the control tower above
// pseudocode
// get the euler angles needed to point at the target
// then, clamp those angles.
the clamp ranges you need are specific to the hierarchy of the turret
you probably made it challenging to decompose the rotation of some simple vector "looking at" the target into the hierarchy you actually have
Why did you just ignore what I wrote and show your implementation
I'm showing you how to do it - try to avoid reading back eulerAngles from the Transform because that gets you into trouble
because I don't know how to reach the float
wdym "reach" it
How can I find the float.
??
My code is super simple withoput clamping, it's just this:
Vector3 direction = (targetPosition - gimbalTransform.position).normalized;
Quaternion wantedRotation = Quaternion.FromToRotation(gimbalTransform.forward, clampedDirection);
gimbalTransform.rotation *= wantedRotation ;
I understand that
but you can't do it that way if you want to clamp
You'll need to define your own rotation variable(s) and drive the rotation from there
That is what I don't know how to do it. Should I use Vector3.SignedAngles to discover those variables?
"discover" them?
No like I said
define your own variables
drive the rotation from those variables
as per my example code
I don't understand how it fits my use case. How can I use your code to rotate to a specific point?
This is for AI, not player input
determine the angle that would be required to aim at that point
then set the angle to that (but clamped)
that's what I called discovering them
Ok yes, you could use Vector3.SignedAngle
basically comparing the turret's normal "forward" direction to the required direction
to find the correct number to use as the angle
then you clamp it
Currently, I have a scriptable object representing a player action. It contains the relevant stats (like the attack action has attack damage and range), and it can also be used to execute the action. In the game, the scriptable object can return a button so that it can display to the user what actions they want to pick. The issue I am facing now is that each of these scriptable objects require a button prefab for that method to instantiate. So if I have 100 of these scriptable objects, I would have to assign the prefab 100 times. I was wondering if there is a way for the method to know about the button prefab without dragging it in via the inspector. I was thinking of a making a factory singleton scriptable object that takes in the button prefab, and has a static method Create(), that returns the instantiated prefab. Is this a terrible idea and I should just have a button prefab field in that my player action scriptable object?
Or is there a better way?
almost definitely just want a single button prefab that can handle any action
Assign it a delegate from the SO as you instantiate it
So drag and drop the button prefab into the inspector window?
something like:
public class MyButtonScript : MonoBehaviour {
Action theAction;
TMP_Text buttonText;
// Call this right after instantiating
public void Init(String actionName, Action buttonAction) {
theAction = buttonAction;
buttonText.text = actionName;
}
// Assign this one as the button on click in the inspector inside the prefab
public void OnButtonClick() {
theAction?.Invoke();
}
}```
Yeah I have something like that
I was just wondering how to get the player action SO to reference this
Because all of the player actions ideally should have the same button prefab, I shouldn't have the ability to drag and drop a different button prefab for two different player actions.
So then you'd have another script doing something like this:
public class SomeOtherScript {
public MyButtonScript buttonPrefab;
public void InitActions(List<MyScriptableObject> sos) {
foreach (var so in sos) {
MyButtonScript instance = Instantiate(buttonPrefab);
instance.Init(so.ActionName, so.ActionMethod);
}
}
}```
OOOOhhhh, okay
But I would have to expose some stuff from the SO
But I get the idea
Thanks
What pattern would you guys go with for a 2D game (point and click) sort of like civ but without 3D elements.
WDym by "pattern"? I'd probably use Unity's tilemap for the hex grid to save myself the trouble of implementing a hex grid.
No, the actual design pattern.
Although honestly Unity's "cell index" layout for hex grids is a bit nonsensical to me
What like MVC?
I'm leaning towards MVC
Idk I think design patterns like that are generally over-engineered and not really great for realtime applications
Definitely I would separate the game model (board state etc) from the GameObject world
?
I'm an MVC enjoyer, I think it's good.
games are usually too complex for well known application design patterns, you will break you design at some point anyway
models can be shared/serialized/networked easily, app has a layer of singletons as the controller and the game objects/ui/input collectors as the "viewer"
I'm asking for suggestions 😄
you definitely want a well defined model for serialization/networking etc... he's right about that
but the distinction between view and controller doesn't need to be so well defined
I understand the fundementals, just looking for suggestions.
i mean, you should just have a single Model.cs class with 20,000 lines of code and pass a pointer to it around, right? /s
🙂
This is advanced talk right?
@chilly nymphFor games and game dev in general, I suggest not overengineering to start and literally proof-of-concept-pyramid your way to success.. ie, build a tiny POC then scrap it and start anew when it's too spaghet - keeping the relevant/useful logic and dropping it into a new project.
That's not what I'm really asking...
What are you asking, then? 😛
I'm a 10th year SE looking for suggestions on what patterns I should use.
👆 like this is ... sort of hard to parse what you mean
I'm leaning on MVVC because it solves all my states as well as systems.
there no good answer to this
really, we've been all there when the best patterns failed
But if you guys can suggest something else I would be open too it.
For sure, and that's why I'm looking for suggestions from here 😄
if it solves all your problems what do you need our advice for?
The design pattern I recommend for Unity is something like:
Model Controller.
Where you have some pure C# classes representing the model (which are serializable etc) and then you have GameObjects that are acting as both the controllers and the Views
Basically GameObjects and their Components are the presentation layer
Mate, you guys seem not to be able to read.
I'm looking for advice.
Have you ever asked a question?
You asked this question. I am answering it. You don't like the answer. Sorry about that. But you asked.
if it solves all your problems what do you need our advice for?
Advice doesn't mean I'm not open to others ideas.
great, and right after that I gave some suggestions
Then why make that comment?
hey,
I have 2 list of Property info
public List<PropertyInfo> oldVarList = new List<PropertyInfo>();
public List<PropertyInfo> newVarList = new List<PropertyInfo>();
how to look for every value in "oldVarList" and see if any variable with the same name/hash/whatever ...in newVarList and if true, try to replace the newVarList var variable value by the oldVarList var value
It's up to personal preference what code design patterns you want to use
Some people like xyz and others will hate it, just do what you prefer, it's your project
Yes, and in trying to find such a pattern I am looking for advice on what you guys have done.
Anyway my point is Unity already has a forced design pattern of GameObjects/Components which you have to overlay whatever you're doing on top of. So I feel it's best not to try to get too pedantic about what's a Controller and what's a View when it comes to MonoBehaviour scripts.
It seems like there's a better way to solve your problem, what are you trying to do?
just give me any example, I dont know much about how to do that
Yes I understand how composition works 😄
Im making a new class ,lets call it "NewClass", which is inherited(based) on an older class lets call it "OldClass" which would look in code, something like this
using UnityEngine;
public class NewClass : OldClass
{
}
the "OldClass" has lots of public variables that were setup on the editor, when I made the new class I found that all those value has returned to default. (in the NewClass component only ofcourse, the OldClass component still has all the public values)
is it possible to copy the variables value of the OldClass to the new one sense they are the same?
for example if i made a new gameobject and added OldClass to it I could simply go the other OldClass gameobject, click on the 3 dots and then copy component >>> back to the new gameobject >> past Component values
What are you actually trying to do?
Make a factory?
I've just answered
factory?
no all what I'm trying to do is what I've just mentioned
That is, you are trying to solve problem X, and you think solution Y would work, but instead of asking about X when you run into trouble, you ask about Y.```
There's a simpler way to achieve what you want @woven kettle just let us know what you are trying to do, what functionality.
Not what your solution is.
To me it sounds like you want a factory.
is it possible to copy the variables value of the OldClass to the new one sense they are the same?
Google factory pattern.
I feel like you're struggling a bit with inheritance and how unity stores serializable data
You can use the MovedFrom attribute to "move the values of a serialized type to another", iirc
ok, the factory thing is not what I'm doing, I do have a new class and I wanna copy the public value I set manually on the editor via script
because manually takes forever even when I tried it, it didnt works because I possibly have missed something
The inspector handles that for all your components.
Would it be an idea to use scriptable objects to store settings and read them?
If you want to create a new class create an object and pass in the constructor or a SO ^
BUT not being rude but a better understanding about classes will help you here.
like game settings that need to persist between play sessions?
you could certainly use them as data containers that persist outside of and between scenes but they don't persist between play sessions, you'd need to serialize the, externally for that
not sure what do u mean by SO, Scriptable Object ?
I'm not really asking the question like that 😅
I meant it as a suggestion for zylog
Yeah I just realized that as he responded to you
I'm drifting in and out of chat my bad haha
Their question isn't about inheritance.
They have a MonoBehaviour, with serialized fields, and an upgrade requires them to use another class, and they want to migrate the values in those serialized fields to the new class.
im down for the easiest way in doing that, I asked that yesterday and many ppl said you are on ur own you have to do it manually 😄 , so I'm happy to know that I have options today 😄
A understanding of classes will help them.
and they want to migrate the values in those serialized fields to the new class. so a factory?
No, automation
its inherited from the same class. instead of doing it manually, I just wanna relay to the script to do it, I dont know if that is called factory or not, but whatever, that is what I want
Their question isn't about inheritance.
You guys need to get your shit together 😄
Factory is utility class that that constructs stuff for you, it's not relevant
just do it by hand, it will take 30m, whatever, next time you wont change core components of your game
https://answers.unity.com/questions/1537920/copy-reference-from-one-component-to-another-deriv.html?childToView=1538287#answer-1538287
first result on google btw
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
You can pass a class to a constructor wherever you want. BUT I don't think this is what you're actually looking for.
Inheritance is one of the solutions they tried. That's not the question
it took more than that and I missed something up, it didnt work... I dont wanna waste my time again, I just a small script that compares the two lists would do it
Are you saying you need to literally copy the inspector values to another component?
YESS!
literally
Copy the fkn component.
it has a different name
he wants those values inside the new component
Well you can't
If it has the same struct you can...
Two different classes
Oh man this question still?
You've been working on this over a day, you could've probably copied the values manually by now
You could hack your way around it with reflection, but I'm not going to go into that 😂
u kept focusing on Factory guess and didnt focus on the question 😄
Also you could try hacking the yaml scene/prefab file to change the script GUID to point at the other script and if the field names are the same it might work 😛
"How do I copy inspector values to a new component" It's not hard. 😄
#archived-code-advanced message check this example again ... oldClass is not the same as newClass
That was mentioned in their original question, the text wall one that also mentioned the things they tried
OldClass != inspector component.
A component is a class lol
It's not a inspector element mate.
Yes it is
i feel like u are talking about something else other than unity 😄
the inspector copy component stuff doesn't work in this case - we have established that
wtf are you talking about, a class doesn't represent a inspector component, it's a layer on top of unity.
A class is a object.
MonoBehaviour : Behaviour : Component : Object
dont mind them, we know your problem, there are multiple solutions, but no one going to just write it for you
A inspector component is not a literal class, it's a representation of a class on top of unities front end.
Lmao
I can copy inspector values from "OldClass" to another "OldClass" ... but I cant copy the inspector values from "OldClass" to "NewClass" because they are not the same.
so my solution to that is to make a script that compares the variables with the same name and then copy the value from "OldClass" to the "NewClass" (even though the "NewClass" is inherited from "OldClass" )
so I have right now 2 lists of PropertyInfo ... and I'm looking for the best way to compare the variable in each
that is all
Just iterate over them all
Who cares if it's O(n^n)
It's just editor code, performance doesn't matter
serialize to json and be done with it.
what's the problem with ```
newComponent.myStuff = oldComponent.myStuff;
newComponent.myStuff1 = oldComponent.myStuff1DiffName;
newComponent.myStuff2 = oldComponent.myStuff2;
why you need reflection for this
well
depends how lazy you are I guess
you either write some reflection code or your tediously write out each field name
that would be a whole new level of laziness
software developer laziness means building crazy tools if it means you don't have to manually copy 50 numbers from column A to B 😆
It would probably take more time using Reflection and making sure it works, than writing it all out
Oh please not a god object
if it's 1000 fields (it's not i know) it could be faster to write the code
somewhere between 0 and 1000 is the sweet spot
Using reflection is guaranteed to take more time
abslutely dont wanna go into making every field, i make mistakes a lot, this could take forever.
could you give me an example of how reflective function would look like ?
with 1000 fields i would just edit the scene file, its just YAML 
It's probably faster than all solutions previously mentioned
Make a backup though, you definitely can corrupt the scene/project if you do something wrong
Do you guys know of a way to automate the NPC creation process? If I were to have x sprite sheets formatted the exact same way, how would I automate splitting each sheet then creating a bunch of animations
Sorry if i did not explain this well, im trying to make tthe chunk that the player is in to generate higher detail
Wikipedia has a good explanation and even some pseudocode https://en.wikipedia.org/wiki/Quadtree#:~:text=A quadtree is a tree,into four quadrants or regions.
never saw that part, thank you very much
Anyone can tell me why it can't find my GO? It's null... The GO is in Scene.
[Test]
public void ShuffleTest()
{
Deck deck = GameObject.Find("Deck").GetComponent<Deck>();
//More stuff happens here
}
- Does the name have any spaces in it?
- Does the deck object exist yet at the time the code runs?
- Is the deck object active at the time the code runs?
- No it doesn't
- It's preconfigured in scene so it should already be there when the code runs I guess
- Yes.
I just created a testing scene, added a Deck GO and added the Scripts to it. Nothing else and nothing happens at start.
this is a unit test though right
Yes
Sec. will check
Dangit, yes you're right
So I should either load the scene in the test method or find a way to create the deck GO, add the Scripts to it and populate the list with the Assets from the Assetfolder..
I htink people usually use like Resources.Load for unit tests
to load a prefab
Or build the GameObjects in code manually with AddComponent etc
is there an aspect ratio fitter component that rescales its contents in UGUI
Yes, it is called Aspect Ratio Fitter, unless I misunderstood.
I know that works with Unity UI, but does it also work with UGUI? Haven't used UGUI myself...
Aaahh, sorry- I don't know.
I'm pooling my ui element, other than the memory allocation. Under the hood is there anything else that is processed? Does anything get dirtied if a canvas / component is off?
pooling a ui element is like the most unnecessary thing to do, unless your game consists of, well, UIs.. 🧐
as in 90% of your game is just.. UIs