#archived-code-general
1 messages Β· Page 129 of 1
or even just in Reset
i believe you will end up with error likes: layer value must be [0,31]...
I don't think so
and it does not throw any errors, just -1 if not found
Eh not a big deal, just an experiment
Does somebody know if there is a possibily to do smth like:
private IEnumerator Bla()
{
// do smth
if (Bla() Coroutine was stopped)
{
print("Stopped");
}
}
so that some action is done, when coroutine is stopped
maybe pass a callback into it
what's that?
and no more yield return after the call back
Bla(Action something)
when finish, calls something() then "yield break"
I actually didn't get anything, sorry
Specifically within the coroutine?
no, it doesn't actually matter
You could maybe do something like
if (!coroutine.Running && coroutineWasRunning)```
I assume there's some IsRunning sort of thing, or maybe check if it's null
oh, not that
I don't think that's what I need π€
it should do some action here:
StopCoroutine(_caretBlinkCoroutine);
_caretBlinkCoroutine = StartCoroutine(CaretBlinkCoroutine());
Why can't you just call whatever method after you stop the coroutine?
I can
If you force stop the coroutine i believe you can just call the callback right after it
I just wondered if there's a better way to do that
yeah, I wonder if I can though
And the callback in ienumerator probably wont be called
IEnumerator One()
{
yield return StartCoroutine(Two());
callBack();
}```
One will yield until Two() terminates
Anyone know what this is stored as for a UnityEvent?
[SerializeField] UnityEvent<object> _event;
_event.Invoke(???);```
I think I should test it. It should work with local Coroutine too I guess
This goes a bit more in-depth: https://onewheelstudio.com/blog/2022/8/16/chaining-unity-coroutines-knowing-when-a-coroutine-finishes
Near the end it even talks about using callbacks.
I think it is possible without callback too π€
itβs completely optional
I made a shotgun that shoots at the position of the mouse. I am having a little bit of trouble regarding the spread. This is the code I have. It works good for the most part but with this method the bullet spread depends on how close the cursor is related to my character. How can I make the spread independent of that?
Vector3 mousePos = Input.mousePosition;
var aim = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane)) - transform.position;
for(int i = 0; i < numberOfBullets; i++)
{
var dir = (Random.insideUnitSphere * spreadDistance + aim).normalized;
rotate towards, but like, for 2d? this is my code
transform.rotation = Quaternion.RotateTowards(transform.rotation, q, rotateSpeed * Time.deltaTime);```
How to debug "The referenced script (Unknown) on this Behaviour is missing!".
Why it doesn't say what object/component is the problem?
This code throws error, does somebody know if that's possible to do smth like that?
_caretBlinkCoroutine = yield return StartCoroutine(CaretBlinkCoroutineHelper());
it does some weird stuff, because it's for 3d and im on 2d
because someone forgot the semicolon
Anyone know anything about this? Going a little bit mad trying to find a workaround to what seems like a simple problem
what?
yield return;(<-this thing)
If you click on the error it will highlight the object that has the script missing. Check the components of that object
StartCoroutine is part of that yield return
no, I need to return Coroutine and store it
they are literally calling yield return StartCoroutine();
ah, maybe then he should make it on the same line?
It doesn't hilgligh anything
i didn;t know, the most common issue is semicolon
// works
_caretBlinkCoroutine = StartCoroutine(CaretBlinkCoroutineHelper());
// works
yield return StartCoroutine(CaretBlinkCoroutineHelper());
it is, your discord window is just so small that it inserted a line break
ah 
it's not
it's not smol
If you run the app, you get the error. Click on the error while the game is still running. If it stops automatically, be sure to toggle "Error Pause"
I tried cliking while game is on, while game is on pause and while game os stopped. Always no result
Then idk π
It will in the log. Click the error and it'll say what line in what file
I do this
var direction = target.position - transform.position;
var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward); /// the -90 was because my object was rotated weirdly
There is no message besides "The referenced script (Unknown) on this Behaviour is missing!".
You need to read the error
When you single click it, there will be a stack trace
ok ill try this ill try this
Just under the log in a separate section
(this isn't c#?)
This is c#
(i want it to move slowly, it is a missile)
Good luck with that xd
bruh
There is no stack trace
There is something like quaternion.lerp. Something like this
timeCount = timeCount + Time.deltaTime;```
Try combining those
I'm not on my PC right now so I cannot show you. Can you screen shot your console window?
Alternatively link the debugger to unity and then run it again.
Thanks, I'll check it
oh my god I hate quaternions
They're not that hard π
If I was at home I would give you my script for a turret
they are if you are working with 2d
It's basically the same. You just need to remove the y rotation
and the x
i think
not sure if someone already helped you fix this, but I believe you have to put it on separate lines
Have you tried rotate towards?
i did, it was really weird on 2d
Vector3.RotateTowards using transform.right
hm
Anyone know if there's a way I can make Parameter serialized in the inspector?
[Serializable]
public class EventPlus<T>
{
public UnityEvent<T> Event;
public T Parameter;
}
[SerializeField] EventPlus<object>[] _eventPlusArr;```
Or if there's any way to invoke a UnityEvent<object> with the parameter from the inspector like in the image below:
```cs
[SerializeField] UnityEvent<object> _event;
_event.Invoke(???);```
E.g.
transform.right = Vector3.RotateTowards(transform.right, targetDirection, speed * Time.deltaTime, 0);```
Event.Invoke(parameter)
more hm
Hey you asked
Event like this?
[SerializeField] Event _event;```
Not sure I follow
Idk what Event is in this context
That's what you wrote
How does physics.sphereCast get it's normal for objects that it hits? Does it return the normal of the face of the collider thats closest to the sphere's origin?
I'm looking for a way to use the parameter you can write into a UnityEvent from the inspector
Like the 5 from the image above
Using event from here
From the part of the collider the sphere hit
Oh right yeah the problem with that one is that Parameter doesn't appear in the inspector when T is an object
working! a million thanks
i have to study quaternions, whenever it comes on rotating i screw up
Seems like this is the only thing I can do but it's very ridiculous
[Serializable]
public class EventPlus<T>
{
public UnityEvent<T> Event;
public T Parameter;
}
[SerializeField] EventPlus<float>[] _eventPlusFloat;
[SerializeField] EventPlus<string>[] _eventPlusString;
[SerializeField] EventPlus<bool>[] _eventPlusBool;
etc
foreach (var eP in _eventPlusFloat)
{
eP.Event.Invoke(eP.Parameter);
}
foreach (var eP in _eventPlusString)
{
eP.Event.Invoke(eP.Parameter);
}
foreach (var eP in _eventPlusBool)
{
eP.Event.Invoke(eP.Parameter);
}
etc```
what is this?
Don't really understand what you're trying to do TBH
A workaround because Unity won't let me use the parameter in the UnityEvent
I just want to do something like:
[SerializeField] UnityEvent<object> _event
_event.Invoke(_event.parameter);```
But there is no _event.parameter
hi I'm programming a health bar system that has a health bar with a shield bar over the health, similar to what you'd find in a fighting game. it mostly works but I'm having an error where the visual for the shield bar doesn't zero out before the health bar starts taking damage. the data is correct but the fill for the visual stops at 0.18181 leaving a part of the shield bar. both the shield and the health have identical code and the fill for the health bar goes to 0. I'm not sure how to fix this. the code is written across 4 scripts. This is where i got the original code from https://youtu.be/cR8jP8OGbhM?t=1077
Stat Manager - https://hatebin.com/tcjgbfklyz, Damage Manager - https://hatebin.com/dneuehugdd, Shield Point Manager - https://hatebin.com/yhsqnkfotd, Shield Bar Visual- https://hatebin.com/vgblqcsqcn
π Get my Complete Courses! β
https://unitycodemonkey.com/courses
π Learn to make awesome games step-by-step from start to finish.
Let's make 3 different Effects for showing Damage Taken in a Health Bar!
β
Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=cR8jP8OGbhM
Sekiro's Vitality Posture System built in Unity
ht...
Ok you're actually joking Unity
eP.Event.Invoke(eP.Parameter);```
This does nothing with eP.Parameter. It just ignores it!
It instead uses the parameter you assigned in the inspector. It's what I wanted but like...what?
So the correct code is in fact
_event.Invoke(null);```
Insane
Bullet Shotgun spread
What's that got to do with code?
A server full of Unity devs, in the Unity discord is pretty much going to say: yes
Also, not a code question, that shouldn't be in here.
Hello! Why I cant access any namespace if I already have the package installed?
https://docs.unity3d.com/Packages/com.unity.code-analysis@0.1/manual/index.html
The DLL in this package are not automatically referenced to your project's assemblies, so you will need to reference all of them in each .asmdef that will require them.
the namespaces are referenced but i cant access the generator attribute
Hi is it possible to make an ingame microtransaction system with steamworks ?
cause for my game that uses steamworks a lot (online multiplayer fps) I think microtransactions are better than DLCs
Best practice question; I have several different types of items inheriting from a base class, whats the smoothest way to check which type an item is?
maybe is, as or GetType()
?
if you have a lot of diff types instead of if statements or giant ass switch maybe is best doing lookup table with dictionary ?
Yeah right now im using an " if item.script is weapondata"
If I turn on gpu instancing from the material and turn on static batching from the editor, will they conflict?
or improve performance 2x
https://partner.steamgames.com/doc/features/microtransactions/implementation
Yes, bu you'll need to add a custom web server that acts as a middle man. The WebAPI can't or may not be used directly from the client (the WebAPI key that you receive should not be included in the build)
How do i finish decalring this:
public class References
{
public List<GameObject> structures = new List<GameObject>();
public List<GameObject> cables = new List<GameObject>();
public List<int> connectedTo = new List<int>();
}
new Dictionary<string, References> references = new Dictionary<string, References>()
{
{"Red1",}
};
To have the same workings of this mess
//input red
public List<GameObject> connectionsRed1 = new List<GameObject>();
public List<GameObject> cablesRed1 = new List<GameObject>();
public List<int> connectionPointRed1 = new List<int>();
//input green
public List<GameObject> connectionsGreen1 = new List<GameObject>();
public List<GameObject> cablesGreen1 = new List<GameObject>();
public List<int> connectionPointGreen1 = new List<int>();
//output red
public List<GameObject> connectionsRed2 = new List<GameObject>();
public List<GameObject> cablesRed2 = new List<GameObject>();
public List<int> connectionPointRed2 = new List<int>();
//output gren
public List<GameObject> connectionsGreen2 = new List<GameObject>();
public List<GameObject> cablesGreen2 = new List<GameObject>();
public List<int> connectionPointGreen2 = new List<int>();
i just don0t know how to declare the value part of the dictionary
new Reference() ?
thanks, but i guess you don't need the brakets
You should review the name of your class. References is pretty bad name for what you are doing there.
why ?
is the list of all the references that my gameobject is storing to other gameobjects
what this rappresent is the connections in a network
Also you might want to do this:
var dict = new Dictionary<string, References>()
{
{"Red1", new References()}
};
You named your class by its function in code instead of by its actual function. What the class represent ? Is it a player ? A node ? A bridge ?
It is like calling a class class.
so i should call it node ?
is tecnically a structure that is then joined to other structure using cables
here is store the connections
I don't know. You know. You are the one creating the object.
It must have a purpose ?
why is this better btw ?
I mean, it compile.
the reason i called it reference is because is litteraly storing references, or should i call it structure references to be more clear ?
No, use the language of your domain.
What are you doing ?
can you be more precise with this question is a bit unclear
What is red, green, blue ?
Hello, does Unity have a specific owner client ID value to represent a null ID? I couldnt find one in the docs.
public NetworkVariable<ulong> CurrentInteractorClientID = new NetworkVariable<ulong>();
I have something like this to keep track of the client that is holding an object, but when its not holding anything, I am not sure what to set this value to. I couldnt find anything in the docs, so I am curious if you all have an answer
Im considering just using the max value for ulong but I dont know if unity has a specific recommendation
the color of the connection
each structure has two type ofg connections, red and green , the can be both inpuit or output
1 and 2 rappresent that, i know those are not clear but i can't really change it
This is even worst
What if you decide to change the color ?
Are you serious O.o
i am making a simulation of something that already exist
if i changed it it would be wrongh
same reason i use 1 and 2 is because the original game uses 1 and 2
doesn-t really make sence because the sprites of the structure use green and red
Is it red then ?
left is imput, right is output
The color has no importance there...
What is the function of the devices ?
this can do math
Alright, so what the red cable does ?
you can use the inputs in the green and red cable and output it to the red and green cable
move data between structures
the reason there are two cables is so you can use the same id without the data adding togheter
So, can we call it something like Link ?
sure
So, a machine has link. This particular machine has two link. You do not need to identify those link inside the class don't you ?
You could have a list of link.
List<Link> instead of a dictionnary.
As you might have other type of machine in the future
One with more than 2 links
all the machine arte the same
they can have only 1 or two links
Alright, I'm done. You understand nothing of what Software Architecture is.
i know what you mean, but because this is a simulation of a game that already exist there is no need to think beyond what the game already is
thanks any way
And friend, this is where you are wrong.
why ?
like i am onestly curious, i not a good programmer at all, so if i can understand software architecture would be just better
Does Unity have some built in Timer class with callbacks I can hook into?
there time.delta time
depends on the purpose
and what kind of callbacks you are expecting
if this is for some sort of gameplay timer then no, although there is a timeSinceLevelLoad property on unity's Time class. you'd have to write your own using a deltaTime timer in Update or c#'s StopWatch class or something
Software Architecture is all about minimizing change to increase the maintainability of a software. With the approach you are taking, you gonna have a hard time implementing the other functionality; Those that are in the game your copying.
To create a solid architecture, you must consider the concept you are representing. You must define what we call Domain-Specific Language (https://en.wikipedia.org/wiki/Domain-specific_language). In your case, that would Machines, Links, Input, Output, etc. If you do not define those concept, you never going to be able to have a stable structure as it will not represent correctly your application. Each Business Rule you gonna implement will always require a reorganization of your structure. You are already suffering from this and you are probably not far in your implementation.
bro is a wizzard
wizzards know everything
i learned everything by myself π§ , so my code runs with spaghetti and tomato sauce
This going to follow everywhere till you have the motivation to make clean code.
is something i always try to do but i don't think is something i can just figuer it out by myself indeed you have a degree for a reason
Self taught is hard but not impossible. You just gotta look further then under your nose.
i am doing this project litteraly because of this, but the problem is that there are many many things to learn
i like learning by being forced to find solution other than studying the theory, at least for coding
Alright, just stayy curious. Because the way you were earlier is the worst way to approach any issue you will have.
check this older code that know i am rewriting
π
π
Ya gameplay timer is what I'm looking for.
i guess what you could do is use time.delta time and count how much time passed, then when you reach the the time you want you call the function you want to call
'ello lads. i ripped off some code and did some experimenting with it, and i am confused by how a certain part of it works. it does work, but i don't understand how: https://paste.ofcode.org/AqUUYq7BnaqE7UvEDJ5YJw
in particular, it's the
//Sets a target position (tbh don't know how this works, but it does)
Vector3 targetPosition = holdPosPoint - selectedRigidbody.transform.position;
``` that i don't get. can anyone tell me what this is doing exactly?
hey guys. Anyone know what's going on with "UnityException: Load is not allowed to be called during serialization, call it from Awake or Start instead." Got this since the new LTS. I just upgraded and this is annoying, even if it works in reality.
think that means something is being incorrectly assigned outside of start or awake
you mean the substraction of two vector3?
i guess that's the wrong part to focus on. i'm confused as to this is getting the correct location for an object to move.
check this. there's an example for exactly that. pretty simple.
like, i get that it's subtracting the vectors, but i don't understand how that's getting me the correct position for what i'm doing.
you substract both of these vector. this gets you the vectorial "distance"
You then change the velocity by using this distance and slowing going in that direction using time.deltatime
targetPos = currentPos + someSpace;
someSpace = targetPos - currentPos;```
Does that sort of help?
"targetPosition * forceAmount" is the same as the substraction but you multiply each of them by this number
to be honest, the example in the doc for velocity is very clear. You should look at it. It's the same thing but simplified:https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
the names donβt make that much sense in your code, but your result is the someSpace(difference) between holdPosPoint and selectedRigidbody.position
this error is more annoying to me lol. Not sure if this is version specific cause I didn't have that in the non-LTS for the same code.
try deleting the library folder and seeing if regenerating it removes the message
weird that it only created the error after you updated 
Aint no better Timer than this https://github.com/akbiggs/UnityTimer
yeah. thanks. already tried that. didn't work.
do you need something that fancy to time stuff? why not just using IEnumerator and yield?
most thing that requires timer, I just use a coroutine personnaly
Well okey, but if you need to time lots of stuff you might as well create some sort of utility class
this does look like a nice library though. avoid a few headaches for creating variables mostly. What do you need something like that for?
And if you do that you might as well use a pre built and tested solution
Damn that is a pretty nice library.
My though as well. I like it even though I don't need it
your point is that it's not maintained anymore?
My point?
Dude wanted a timer with a callback
i gave him a timer with a callback
There is no point here to be had
oooh. I though you were asking the question lol. my bad
We use this lib in our games and are very happy with it so I share it with people who need to time stuff
Hmm. Do the timers work across scene changes?
It doesn't seem like the TimerManager has DontDestroyOnLoad
store the result between scene or something?
or just dont destroy one class in which you have it initialized
Right. I think we made it a singleton a while back
https://medal.tv/games/requested/clips/1eNHMUeJEcuQI4/d1337XRkawIY?invite=cr-MSxKTnYsMjYzNjQxOTcs
Hello,
I am attempting to make a restaurant game and the npcs coming in are supposed to sit down (animation) after their transform being set to a gameobject's transform
For some reason there is always an offset on the y - Axis, I am not sure why
I am also unable to move the object's Y axis in runtime
Components:
Rigidbody
2x Colliders (one with, one without trigger)
Navmesh Agent
Script
Animator in the child object
private void OnTriggerEnter(Collider other)
{
if (other.name == "WalkToPos")
{
nav.ResetPath();
animator.SetBool("isWalking", false);
nav.updateRotation = false;
Rigidbody rigidbody = GetComponent<Rigidbody>();
rigidbody.velocity = Vector3.zero;
rigidbody.constraints = RigidbodyConstraints.FreezeAll;
StartCoroutine(CustomerSit(other.transform.parent.Find("SitPos").gameObject));
}
}
IEnumerator CustomerSit(GameObject sitPos)
{
yield return new WaitForSeconds(0.4f);
transform.position = sitPos.transform.position;
print(transform.position + " " + sitPos.transform.position);
print(transform.position);
transform.localRotation = Quaternion.Euler(0, 0, 0);
transform.rotation = Quaternion.Euler(0, 0, 0);
Animation customerSitAnim = GetComponentInChildren<Animation>();
animator.SetBool("isOrdering", true);
ChooseRandomItem();
sitting = true;
}```
Watch Bug Help 18/6/23 and millions of other Requested videos on Medal, the largest Game Clip Platform.
what's the best way to make an infinite looping scroll? I know there's assets but im trying to figure out how to do it myself. I initially tried doing an invisible "teleport" once I go past a boundary, but if I drag past, say, 0.8 and try to teleport to 0.2, dragging further will continue to take me past 0.8. then it just flickers because it tries to teleport again.
now I'm thinking of doing a dequeue system, but I still run into the same issue.
no, that's not my problem
I need to yield return Coroutine (as you have said before) to wait until coroutine is finihsed and this coroutine should be _caretBlinkCoroutine
So it's possible to do _caretBlinkCoroutine = StartCoroutine(CaretBlinkCoroutineHelper());
and possible to do yield return StartCoroutine(CaretBlinkCoroutineHelper());
but this is impossible
and that's what I am trying to achieve:
private IEnumerator CaretBlinkCoroutine()
{
_caretBlinkCoroutine = yield return StartCoroutine(CaretBlinkCoroutineHelper());
IEnumerator CaretBlinkCoroutineHelper()
{
WaitForSeconds _caretBlinkRateWait = new WaitForSeconds(caretBlinkRate);
while (true)
{
yield return _caretBlinkRateWait;
ChangeAlpha(0f);
yield return _caretBlinkRateWait;
ChangeAlpha(1f);
}
}
ChangeAlpha(1f);
void ChangeAlpha(float alpha)
{
Color newColor = _caretImage.color;
newColor.a = alpha;
_caretImage.color = newColor;
}
}
you don't need the startCoroutine in an IEnumerator
yes, but how do I assign it now?
i have a bunch of buttons in a scrollrect, is there some way to reorder them during runtime
set parents
If you have access to "Content" you could use the transform.SetChild and GetChild, when you loop through with childCount in a for-loop, or a foreach loop if you prefer
@gray mural What are you trying to achieve exactly? I might be missing the context of what you're trying to do here.
I am trying to make it so that if you end Coroutine - it can say its "last words"
for example when I do:
StopCoroutine(myCoroutine);
it does something at the end (e.g. "bye bye" in console)
do you mean StopCoroutine?
yes, sorry
In general, this is considered bad pratice to use stopCoroutine. Just because there's proabably a better way. You can't really know where the coroutine will actually stop. If you need a very specific behavior to happen, you won't have control over when it does stop.
controlling the when using variable or something else could be an option.
From what I get, you want to get your caret to flash once and then do something, right?
Why not in this case have a variable global to your class, call it "endCaret" or something. And in your coroutine, you have yield waiting for this to happen, and then trigger whatever you need.
yield return new WaitUntil(endCaret);
If the endCaret variable is a Coroutine type, you should also be able to call something like yield return StartCoroutine(endCaret); or endCaret = StartCoroutine(...); yield return endCaret;
this coroutine stops everytime user types smth in custom InputField.
caret is constantly blinking
and when coroutine stops - caret should imediately become visible (alpha 1f)
it just calls coroutine twice
and it won't call endCaret = StartCoroutine(...); until endCaret Coroutine is not finished
I wonder if that works with my while loop
Really? Interesting, I was using something similar earlier today for a rebind system and some logging and seemed to only happen once, though I often have a function to manage coroutines with variables, something like:
Coroutine co;
void DoThing(IEnumerator next)
{
if(co != null) {StopCoroutine(co);}
co = StartCoroutine(next);
}
That wouldnt be the same as yielding it inside a coroutine though, just would prevent multiple coroutines from starting if the previous one wasnt finished (or reset to null) already
that's already basically a while loop that checks for a condition
so you have a coroutine checking the content of that field? or is that event based?
I feel like the solution to your issue isn't really a coroutine but simply an event.
If you have a class to manage that inputField, you should have a property for the content of it.
If you have something like this:
just figured i could unload all the projects i dont need in the solution and hide them
instant vs speedup
public event Action<string> OnInputChanged = null;
private string _input = "";
public string Input {
get => _input;
set {
if (_input != value) {
_input = value;
OnInputChanged?.Invoke(_input);
}
}
}
Then, you call it where you need it:
Input.onInputChanged += Somefunction;
private void Somefunction(string value) {
if (value==="smth") {
StopCoroutine("caretAnimation");
}
}
@gray mural Or that could be a simple function inside the set instead of an event if that's suposed to apply to any input whatsoever. litle less flexibility.
That coroutine could be on the class of the inputfield itself, and you could call it to start and stop the caret animation using the same technique.
=== ?
!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.
also #archived-shaders
oh sorry
Sorry for late reply. So that should work, yes. I was just considering to make this in one coroutine though, but this is great too. Thank you
I guess no ?? This method is called by Event though
like this:
private void KeyDownEvent(Event evt)
{
switch (evt.keyCode)
{
case KeyCode.Backspace:
BackspaceKey();
return;
case KeyCode.Delete:
return;
}
ValidateInput(evt.character);
}
private void ValidateInput(char c)
{
if (c == '\0' || c == '\t' || c == '\n')
return;
text += c;
AlignCaret();
}
though I wonder why I need to use event here. Isn't it redundant?
@honest edge @soft shard thank you both for your help, that's the solution I have done after all:
private void CaretBlink()
{
if (_caretBlinkCoroutine != null)
StopCoroutine(_caretBlinkCoroutine);
ChangeAlpha(1f);
_caretBlinkCoroutine = StartCoroutine(CaretBlinkCoroutine());
IEnumerator CaretBlinkCoroutine()
{
WaitForSeconds _caretBlinkRateWFS = new WaitForSeconds(caretBlinkRate);
while (true)
{
yield return _caretBlinkRateWFS;
ChangeAlpha(0f);
yield return _caretBlinkRateWFS;
ChangeAlpha(1f);
}
}
void ChangeAlpha(float alpha)
{
Color newColor = _caretImage.color;
newColor.a = alpha;
_caretImage.color = newColor;
}
}
If you already have something to handle it, yes it is. It was just the idea
I have this process that I want to handle
right now I do it via 2 scripts like this:
public class Interaction : MonoBehaviour
{
public UnityAction onInteractEvent;
private Transform aim;
[SerializeField] private float range;
private void Awake()
{
aim = GetComponentInChildren<Transform>();
}
public void Interact()
{
// Shoot raycast and return hit object (or null)
RaycastHit2D hit = Physics2D.Raycast(aim.position, aim.right, range);
if (hit)
{
GameObject hitObject = hit.transform.gameObject;
TryInteractWithObject(hitObject);
}
onInteractEvent?.Invoke();
}
private void TryInteractWithObject(GameObject objectToInteractWith)
{
if (objectToInteractWith.TryGetComponent(out Interactable interactableObject))
{
interactableObject.TriggerInteraction();
}
}
}
Both scripts are the same except one does TryInteract and one does TryHit
how can I avoid this code duplication?
is there any way the basic unity ads can mess up a game? I had a working mobile game, and wanted to add the ads. but now its completely broken. the starting screen doesn't show text anymore and when i click the (only) button to start the game it gets stuck on an infinite loop clicking itself and doesn't start the game. tried looking into the logs with logcat but couldn't find anything
well i found the problem. it was the ads initializer i added on the starting screen. when i removed it, the game works fine. anyone would happen to know why?
Well, first off, do you have a case where a gameobject is both hittable and interactable? If so, is there priority to what you check first?
I don't plan to but if there is such a case, interaction happens via the E key while hitting is via Mouse1 so they won't have to be checked concurrently
I'm thinking of just splitting the big script into a Fire() script, a Raycast() script, and then I can apply either a Interact() or Hit() script
i feel like interfaces could be useful but im not 100% sure when to use them,
I can communicate the scripts via unity events
Usually when I think of interact scripts, they are usually done without needing to know the exact derived type that's hit, and as such you just use the override methods of your implementations
Interact keyword meaning that there's some sort of functionality that you can do with the object, either attack, talk, trade
so my enemy is just a health component, collisionattack component, AImovement component. There is no concrete "enemy" class or anything
Is this through inheritance?
Yeah, via virtual function implementations
ah i see, my project is just structured too differently
not entirely sure of a composition or an ecs type of way
if anything, a switch of checks might be what you need
but this still comes to my previous question about having multiple interface types
though if you've got differeny raycast methods depending on input then that's not a problem
Hey im trying to setup a position constraint for the purple aura in my game. But adding a new constraint source doesnt apply any constraint to the gameobject. I am confused on how to use the position constraint and untiy script documentation doesnt help me either
I think there may be values you need to toggle with the constraints when you create one
I forget
It's like weight or something
ah found it thank you
how can i check if a bounding box of one object is inside the bounding box of another object ? im currently cecking it like this but it wont stop scaling down the object
im scaling it down when the second bounding box isnt inside the first one and it should theoretically stop once the second object has been scaled down enough to fit into the first object
its for an inventory system
thats right
maybe put extra true statements in? right now you're checking if the first one is false or the second one is false. but not one false and the other true. so when they're both false it still runs the code
vscode question. How do i move the "2 references" to the right?
it means it's used on 2 different locations in the code. here's a stackoverflow post that might help disable it
https://stackoverflow.com/questions/34356510/how-to-disable-codelens-in-vs-code
oh so it's called a codelens
yikes so apparently they don't have the feature to move it to right like in intellij (illustrated below)
disable codelens, use search in options
we have a feature to remove it tho, best feature ever
yeah couldn't look cleaner
you should bind a hotkey to find references
can anyone familiar with zenject help me make a dontdestroyonload singleton equivalent? i just picked up zenject and im confused to say the least ._.
Is there a way to load all scenes once you open the game? There are some scene in my game with some script that I need to load as soon as the game launched. The reason is These scripts generate some data that I need on the first scene.
thats exactly the reason Im asking for help here
create an empty scene that does whatever loading you need
you could put everything you need in the first scene and then load additive
I cant really. is there another way?
you can use RuntimeInitializeOnLoad
it has params that allow you to run code before scene loads
I have an array of bools in one script, like this: public bool[] cubeList = {true, false, false, false};
and I save this to a json file, If i launch the game for the first time It makes a an array of bools without any value.
So the game wount work cuz I need those values
create an empty scene, set it as the first, do whatever loading you need, then load from that scene the actual game scene
its a very common pattern
sure thanks
or use RuntimeInitializeOnLoad
just one more question, I should use singeltons to share the data right?
you could
singletons are the most basic global access pattern, its always present in any game, in various amounts
should you? depends on your project and your skill level
there are alternatives that grow in complexity in an attempt to remedy the shortcomings of it
mr cache do you know anything about zenject?
so if i bind something to it, it should remain in the next scenes?
i didnt but i read about project context so i thought the way to do that would be with it
i dont understand whats the use of the project context then
I added it to my first scene and it doesnt seem to make another instance on the next scene
my problem is im trying to get my data from firebase and bind IDatabase to that instance and only then to load the next scene
it says any scene that contains scene context will first load project context
after that it will singleton DDOL for the lifetime
yea ik its project>scene>gameobject
idk why but these docs are very confusing to me
should i add the project context to my first scene?
i dont know how extenject handles it, i dont think it needs to be present in any scene
i dont think i should cause its a prefab
it should be a prefab that is automatically instantiated
yea so then how would i inject FromInstance
ive been stuck on it for hours chatgpt doesnt help unfortunately
so your issue is that binds on project arent injected in scene?
sound about right i think
from what i understand project context binds whatever i need once and thats it for the rest of the game runtime
thats probably where im not doing things right
in the first scene do i need a scene context?
cause all im doing is binding to the project context (so far) and as you said ^^
i tried doing that with the database instance being ddol and loading scene additive both dont work
validation passes?
yep
public abstract class DatabaseDependant : MonoBehaviour
{
protected IDatabase _database;
[Inject]
protected virtual void Construct(IDatabase database)
{
_database = database;
}
protected abstract void LoadData();
public class CurrencyManager : DatabaseDependant
{
protected override void LoadData()
{
print(_database == null);
print(_database is null);
Pawins = (float)_database.GetValueFromDatabase("Pawins");
Pawllars = (uint)_database.GetValueFromDatabase("Pawllars");
}
basically prints "True" at these debugs
NullReferenceException: Object reference not set to an instance of an object
its called from start
can you put a breakpoint in Construct and LoadData
see in which order they are called
and observe _database value
i can but ill mention i even tried making start ienumerator and wait 5 seconds
and it still said its null
then just in Construct
mmkay
its totally different from breakpoints in normal programming one sec ill google how to do it in unity
its the same, highlight the line in visual studio, press F9, press F5 to connect to unity, play in unity
you arent hitting it?
nope
then you have something broken in zenject scene/whatever that mono is on setup
zenject ignores it
do i need a scene context on that scene?
possibly, it may be needed by zenject to indicate that scene scene is zenject enabled, maybe to perform scene initialization
most likely what it does is it loads first since its high in SEO, disables all scene objects before they have a chance to receive Awake, initializes/injects them, then enables
so i have a projectcontext in my first instance with an installer on it binding from instance, and an empty scene context in the next scene and it says
ZenjectException: Assert hit! Tried to create multiple instances of ProjectContext!
maybe my whole approach is wrong how would i go about doing what i need
load the snapshot from firebase, bind that instance, load next scene and have it injected where needed
anyone know how to detect when a vr player pulls a controller towards themself?
not a VR dev, but I assume you can simply use the controllers XZ distance from the headset's XZ coords, ignoring the Y? If the distance delta over a certain amount of time is greater than your threshold, then make shiny things happen
Or, to ignore the potential bias caused by dragging the controllers ahead of you but towards the center of your body, you could figure out the forward vector that represents the facing direction of the player, negate that vector, and see how far the controllers have traveled along that vector
which I'm guessing the only harder part about this is determining the player's forward vector if it's not persistent in your game, and if there aren't libraries that already do this. Likely inferred from the controllers orientation and the headset's over a set amount of time
Im using the textmesh pro TMP_Dropdown UI element and im adding items to the dropdown menu through code. I then want to add a method in their OnClick() event, how could I do this through code?
loop through the array of items
Yo, I have a question...
How do I save a 2D/3D array which is being generated by my AssetPostProcessor on a ScriptableObject so that's it available during game runtime?
[field:SerializeField]
public float[][][] array3D { get; private set; }
My method for generating the array is being called, but it's null at runtime
unity does not support serializing multidimensional or jagged arrays so you'd have to store that data some other way
Oh, I see..
[Serializable]
public class MyArray<T>
{
private T[] elements;
public T this[int index]
{
get => elements[index];
set => elements[index] = value;
}
}
[field:SerializeField, HideInInspector]
public MyArray<MyArray<MyArray<float>>> array3D { get; private set; }
Would that be ok then?
You're better off flattening the array.
public T this[int x, int y, int x]
{
get => elements[x + WIDTH * (y + DEPTH * z)];
set => elements[x + WIDTH * (y + DEPTH * z)];
}
Then your constructor would be something like:
public MyArray(int x , int y, int x)
Making sure to save the width, height and depth.
Then it'll save as a single array
[Serializable]
public class MyArray<T>
{
private T[] elements;
public T this[int index]
{
get => elements[index];
set => elements[index] = value;
}
public MyArray(int size)
{
elements = new T[size];
}
}
[field:SerializeField]
public MyArray<MyArray<MyArray<float>>> generatedPattern { get; private set; }
public void GenerateAttack()
{
generatedPattern = new MyArray<MyArray<MyArray<float>>>(repeatCount);
for (int r = 0; r < repeatCount; ++r)
{
generatedPattern[r] = new MyArray<MyArray<float>>(inBatchBulletCount);
for (int i = 0; i < inBatchBulletCount; ++i)
{
generatedPattern[r][i] = new MyArray<float>(batchCount);
}
}
...
Oh. That also makes sense.
Thanks
for accessing a[i][j][k] it should be i*sizeof(j)*sizeof(k)+j*sizeof(k)+k, the order of your indexer looks a bit different though it works but i j k have to be inversed
As long as you stay consistent it wouldn't matter even if you reversed it
!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.
Any easy way to generate a visual grid like this?
I tried with line renderer and gyzmos but all I get is a square in the middle of the map
show what you tried
i use handle and gizmos to show visual grid and debug infos...
First I tried to generate cubes arround but every single one spawns on the same spot
private void GenerateCubes()
{
// Obtener la posiciΓ³n del GameObject
Vector3 position = objetoActivo.transform.position;
// Generar los cubos en las posiciones alrededor del GameObject
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
for (int z = -1; z <= 1; z++)
{
// Excluir la posiciΓ³n central
if (x == 0 && y == 0 && z == 0)
continue;
// Calcular la posiciΓ³n del cubo alrededor del GameObject
Vector3 cubePosition = position + new Vector3(x, y, z);
// Instanciar el cubo en la posiciΓ³n calculada
Instantiate(cubePrefab, cubePosition, Quaternion.identity);
}
}
}
}
Then with LineRenderer but only a square in the middle if lucky
private void GenerateGrid()
{
// Obtener la posiciΓ³n central del GameObject
Vector3 center = transform.position;
// Calcular el tamaΓ±o del cuadrado
float halfGridSize = gridSize * 0.5f;
// Calcular las posiciones de los vΓ©rtices del cuadrado
Vector3[] squareVertices = new Vector3[]
{
new Vector3(center.x - halfGridSize, center.y, center.z - halfGridSize),
new Vector3(center.x - halfGridSize, center.y, center.z + halfGridSize),
new Vector3(center.x + halfGridSize, center.y, center.z + halfGridSize),
new Vector3(center.x + halfGridSize, center.y, center.z - halfGridSize),
new Vector3(center.x - halfGridSize, center.y, center.z - halfGridSize) // Repetir el primer vΓ©rtice para cerrar el cuadrado
};
// Configurar el LineRenderer con las posiciones de los vΓ©rtices
lineRenderer.positionCount = squareVertices.Length;
lineRenderer.SetPositions(squareVertices);
}
Its my first time using this stuff anyway
Hey, it's my first time using BoxCast and I'm trying to make a simple ground detection for my character, for some reason the BoxCast it is only returning true for 1 frame when the character hits the ground instead of always being true
I'm not sure if it this is how it works or if I'm doing something wrong
{
Gravity();
isGrounded = GroundCheck();
rigidBody.velocity = new Vector3 (transform.forward.x * horizontalMovementInput * standWalkSpeed,
rigidBody.velocity.y,
transform.forward.z * horizontalMovementInput * standWalkSpeed);
}
void Gravity()
{
rigidBody.velocity = new Vector3 (rigidBody.velocity.x, -gravityValue, rigidBody.velocity.z);
}
bool GroundCheck()
{
if(Physics.BoxCast(transform.position, groundCheckBoxSize, -transform.up,
transform.rotation, groundCheckMaxDistance, groundCheckLayerMask))
{
return true;
}
else
{
return false;
}
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawCube(transform.position - transform.up * groundCheckMaxDistance, groundCheckBoxSize*2);
}```
sphere/box/capsule casts ignore any colliders they start in
I see so if I cast it inside the ground collider it won't return true
Any way to work around that?
You can combo it with an overlap box query.
I do that in one of my games. The big monster enemy needs to know when the ceiling is too low to stand upright
so I do a combination sphere cast and overlap to get the amount of headroom
Never heard of overlap box query, how exactly does it work?
You ask for every collider that overlaps with a box.
you can also just ask if anything overlaps a box at all
So you can share some of the parameters with the box cast
A box overlap might actually make more sense here
(so, you would discard the boxcast)
I see, I'll try it! Thank you!
<@&502884371011731486> the spam was posted in many channels
yup
Yea working on it. Bot is taking it's sweet time
Ah, gotcha. I did notice it's been chugging today.
Hello, i have problem with netcode for gameobject. When i try to move a cube like in this code for exmeple on Host the cube scale stay on basic scale but on client the cube turn on scale *2. on my cube there is network object and network transform so i dont understand.
using Microsoft.Cci;
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
public class Reveal : NetworkBehaviour
{
public Transform boule;
public bool hasMoved;
private Vector3 startPosition;
private Vector3 endPosition;
private float speed = 3f;
private float journeyLength;
void Start()
{
hasMoved = true;
startPosition = transform.position;
endPosition = startPosition + new Vector3(0f, 0f, 0.4f);
//journeyLength = Vector3.Distance(startPosition, endPosition);
}
void Update()
{
float distCube = Vector3.Distance(transform.position, boule.position);
if (Input.GetKeyDown(KeyCode.E))
{
StartCoroutine(MoveCube());
BouleRougeServerRpc();
}
}
[ServerRpc(RequireOwnership = false)]
void BouleRougeServerRpc()
{
BouleRougeConfirmClientRpc();
}
[ClientRpc]
void BouleRougeConfirmClientRpc()
{
StartCoroutine(MoveCube());
}
IEnumerator MoveCube()
{
hasMoved = false;
float elapsedTime = 0f;
while (elapsedTime < speed)
{
float fracJourney = elapsedTime / speed;
transform.position = Vector3.Lerp(startPosition, endPosition, fracJourney);
elapsedTime += Time.deltaTime;
yield return null;
}
transform.position = endPosition;
}
}```
Hello there, I have been reading a bit about abstraction, and right now I canΒ΄t figure out which scenarios are suitable for each type of asbtraction, so lets say, when should I use interfaces over inheritance and when should I use abstract classes over the 2 abstraction methods I mentioned? Any help is appreciated!
What are the specific use cases for them?
Do you mean factory pattern?
if you haven't already, the best place for everything patterns realation is refactoring guru: https://refactoring.guru/design-patterns/abstract-factory
and for unity specifics, I like Jason's videos
Check out the Course: https://bit.ly/3i7lLtH
I'm giving away another Oculus Rift - https://unity3d.college/giveaway
The factory pattern is a great way to create your objects. You can use it to defer creation of objects when you don't know at compile time what you'll need. In this video, I'll show you some examples of where this patt...
I am fairly new to design patterns but form what I understand, this is pretty much what I described
these two sources will get you probably 80-90% of the way
Ohhhh, okay, I will take a look into it!
Great, thanks you so much!
This is great to start thinking in pattern right at the start of a project to avoid being stuck to old code that doesn't fit and refactor a lot
Yup, IΒ΄m learning this wayy too late, but I have an old code I want to use this pattern into
As some scripts I have are pretty much clones
So I have a player health script and then an AI health script which is the exact same thing but with extra stuff
not all patterns are applicable to unity or gaming in general, but here's another source for more gaming focused pattern design
Got it, I will check which pattern suits best my use case
if you get through all videos from Jason, you'll find the right fit I'm sure. Factory and Command patterns are the most common imo
more game design focused
Very useful info, thank you very much!
to your specific case, maybe start here: https://www.youtube.com/watch?v=ll6bxQGkyCk
Check out the Course: https://bit.ly/3i7lLtH
Learn how to use the Interface Segregation Principle in your Unity3D projects. Create many small targeted interfaces instead of one large one so your code is cleaner and easier to reuse.
More Info: https://unity3d.college
Join the group: http://unity3d.group
I'm pretty sure that's what you're looking for
Seems like it, yeah, thanks!
How can I get data from a collided object. for example if I collide with an object it gets it's damage value (stored in an int) and saves it in some variable?
the Collider / Collision paramater in the Collision/Trigger method
yeah I did that but I can't seem to find a way to get the variable out
eg
void OnCollisionEnter(Collision collision)
{
if(collision.collider.TryGetComponent(out MyHealthScript healthScript)){
healthScript.Damage(10)
```
who owns the cube, and who is modifying the cube?
TryGetComponent
will attempt to get the Component(Script)
then put it in a variable you can use eg "healthScript"
then get your access that way.
variable should be public
but good practice is to make methods instead of directly changing vars imo
@idle oxide
This worked thanks!
In both cases if it belongs to the client if it is he who modifies it or vice versa when he is modifying the client always finds himself with a cube of a scale multiplied by 2
I am playing around with a small "tycoon style" 2D game in unity, where the player can place buildings that do things, thats the main idea, now I am not sure how to do this, I dont want to have everything on a grid so I want to be able to freely place the buildings, initially I just had a GameManager and a List of IBuildings that keep track of all the buildings that have been place but that seems just goofy, they should just be in the game and work without needing to be stored in a list
so what is the actual question ?
How do I keep track of my buildings without having them in a list?
I wnat to collision check when placing buildings for example
use colliders
raycasts
- boxcasts
Okaaaay, I have colliders on the buildign prefab
I don't see a problem with having a list of buildings.
also yeah ^
is good for you to keep track of your buildings spawned or to be spawned etc..
Well sure the list itself is not bad maybe, but iterating all my building to check collisions seems stupid since there is already a collison system
yeah def don't do that
you'd have to keep track all bounds and rotations
it makes no logistical sense if you did that
indeed
And also in that case, my buildings are GameObjects obviously but they also have the IBuilding interface that seems a bad pattern to me comign from C++ where I store IBuildings that are also GameObjects which is not visible
using interface is a good way to look for Building through collider raycast hit
if(hit.collider.TryGetComponent(out IBuilding building))
though to check if things are "blocked" use a the other Physics functions
the bulk sized ones
and not rays
use rays mostly to find a spot on grid from camera pointer ig if its not a controller based
But with the IBuilings, I have the problem that if I store them az IBuildings then I could just add a new building into the list but they should all have game objects too
This feels goofy
if a building is always on a GameObject, then make an abstract class that derives from MonoBehaviour
you probably want ScriptableObjects to hold specific data for each building type
that too: they can contain read-only information about buildings
Ah wasnt sure I could just inherit monobehav with an abstract class
so abstracty class not interface and I can make it always a game object
if its monobehavior it has all the access to gameObject is on
this would not be a GameObject
it would, however, always be attached to a GameObject
Hello how to deal with fps arm and gun not rotating vertically just horizontally, the gun has a parent called Weapon holder that is a child of the right hand of the player, also the player is animated
Makes sense yeah okay thanks, I will do that, it makes more snese with that in my head
Thanks
uh show what you mean, rotations are tricky by description only
How could I do this using Triggers so I don't fully collide with the object because I don't like that it stops velocity?
_targetDirection = _playerInput.Player.Move.ReadValue<Vector2>().normalized;
Vector2 _targetMouseDelta = new Vector2(_mouseLook.x, _mouseLook.y);
_currentMouseDelta = Vector2.SmoothDamp(_currentMouseDelta, _targetMouseDelta, ref _currentMouseDeltaVelocity, _mouseSmoothTime);
_xRotation -= _currentMouseDelta.y * _sensitivityX;
_xRotation = Mathf.Clamp(_xRotation, -75, 75);
_mainCamera.localEulerAngles = Vector3.right * _xRotation;
transform.Rotate(Vector3.up * _currentMouseDelta.x * _sensitivityY);
make collider trigger and use this instead
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
or use kinematic rigidbodies, so that they aren't affected by physics.
of course, in that case, you'll need to control the movement yourself
ok this helps, but do you have a video or screenshot I meant
1 sec
if i parent the gun holder to the camera then the weapon rotates vertically with the camera but that leaves the hand and also the gun wouldn't position and rotate correctly with the hand
how do games handle that
Hello there, I am struggling to understand the implementation of this event, I want to subscribe to an event from my player health controller to my game manager script and then call a function inside of the event manager once this event is triggered.
So this is how I am defining my event
public class GameManager : MonoBehaviour
{
public event Action OnHealthDamage;
public void NotifyHealthDamage ()
{
Debug.Log("damage dealt");
hitCrosshairAlpha = 1;
inQueue += 1;
}
}
And on my health controller I subscribe to that event, but my question is, how do I trigger NotifyHealthDamage once that event happens?
make it MP4 cause m4v not working on discord
shoot
OnHealthDamage?.Invoke()
In my case I made a GameObject that contains the mouse look script (camera) and inside of it I placed the weapon manager that contains all of the weapon models
I tried doing this from the player health, but it gives me this error
Hello!
So I have a weapon system that I want to improve but I'm not sure how to go about it in a way that would also keep the code clean.
I have a base class called "Weapon" in which I keep all the common properties and behaviors of a weapon and two other classes that inherit from it: WeaponHitScan and WeaponProjectile. WeaponHitScan uses raycasts in order to simulate bullets being fired and WeaponProjectile instantiates physical projectiles that detect collisions.
My problem is with regards to the way this weapons can fire. I want both hit scan weapons as well as projectile based weapons to be able to fire one shot at a time(suited for revolvers, pistols, rifles, machine guns, etc.) or multiple projectiles at once(suited to shotguns).
I know how to implement the methods that can simulate accuracy and spread but I'm not sure where should I place them in order to make sure I can create hit scan weapons and projectile based weapons that can fire in any of these two ways.
Any advice would be appreciated. Also, please let me know if you need more details. :)))
ok but how do you manage to make the animated arms of the player move vertically with the camera too
I used Inverse Kinematics for this purpose
I think you can only Invoke an event from the class declaring
you can call the method that invokes it though if its public
so the arms follow the gun
I'm not 100% on that just verify that
But I dont understand, what would be the point of using events if I can just call the method on the game manager to do what I need?
I could simply do manager.NotifyDamage() with no events, right?
I have added this to my building script to check if it is colliding (via its interface)
But I get two things, first, it is always colliding and second I get this error in the console, if I remove the event functions it goes away
thats why you SUBSCRIBE from another class
you dont invoke from another class
Well, I am doing this from the other class
manager.OnHealthDamage += takeDamage;
But now, inside the manager script, how can I trigger a function / bind a function to that event
Ahhh wait
manager.OnHealthDamage += takeDamage;
thats what this does
Invoke should work
wdym takeDamage gets called every time you Invoke OnHealthDamage
Nvm, I dont get it
it's very simple
like Youtube, you subscribe to a channel you want notifications from
+= subscribe to event
But that would bind a function from the player health class
What Im looking for is subscribing to an event, and performing the logic on the game manager script, not the health script
huh?
NotifyHealthDamage () is already doing that
put a method call in there?
i don't understand
what is your use case exactly cause is not making sense to me what ur doing
no reason to sub to your own event.
unless ur a child class or something
I am probably missunderstanding how events work, I will show pictures to better represent what I want to do
So this is inside my game manager class, this is the function I want to be performed once that event is triggered
and from the health class, I want to subscribe to that game manager event and trigger it whenever takeDamage happens
Yes, I added a left arm and right arm gameObjects so I can customize the arm positions there
you're doing it backwards then
So I am supposed to perform the logic from the class in player health instead?
you want TakeDamage inside of health to do NotifyHealthDamage ?
so event should fire from Health script
then manager subs to it
Exactly
Ohhhh
yeah so its backwards lol
define event/ and invoke event, inside of health script
subscribe from Manager
That makes complete sense, let me try
But considering there can be multiple players, how would I subscribe to that then?
subscribe to multple players with a loop
Ahhh, so there is no other way to that
like foreach(var healthScript in playersList)
healthScript.OnHealthDamage += HealthChangeNotify
ideally you can send the info of Who sent it as well if you add that in your Action
like Action<PlayerHealthScript> or just Player

I actually dont understand, I have added a rigid body and a collider to my buildings and I am listening to the OnCollisionSaty2D event to chekc if I can place a new building, (when trying to place something, I create a new GameObejct that follow the cursor position) but I never recieve the event even when I am hovering over an existing building
This code is not terribly complex with a lot to go wrong...
I know that it is not functional because if I ever once collide it will always fail
But it NVER fails as is
I started with enter/exit s but I was like maybe this is simpler for debugging
But nope, never get the event
Every building has a static rigidbody2d and a box collider2d
This is the collider and rigidbody on the prefab
What is the best way to learn csharp? Is it those long course videos on YouTube smth else. I followed brackeys 8 episode series for the beginner stuff but now donβt know what to do
c# specifically ?
learn to make console apps π
get down and gritty to logic only without worrying about UI distractions
Ok thanks
https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2022 @timber jewel
Consider checking out the tutorials pinned in #π»βcode-beginner
Thanks
I am trying to use Relay with NGO but while I can connect my player to the host the client player cannot move I'm not fully sure why
Player Controller: https://gdl.space/asomahebem.cs
Relay Script:https://gdl.space/rexinegayo.cs
am i doing something wrong here, i made a flappy bird like game and i want to make it so when the bird goes off the screen at y=17 then the game ends and it restarts, i dont get it am i doing something wrong (ps. theres no error code when going off screen)
you have posted it 2 times on #π»βcode-beginner already
have you realised that this is a complicated issue?
Seems like a prety dumb/generic c# question but how would you all do this, use regex maybe?
I have some text blocks like "Press [Keybind] to do something" where I want to replace text within the square brackets with some other strings.
How would you all go about isolating/replacing bracket contents, even in cases where you have "][" or other potential invalid bracket pairs.
Feels like a simple interview question lol
give us an example, maybe?
Sure, a lot of these messages are in the game on inspectables.
I already have the string values looked up from user settings.
I just want to replace the inner text
like:
bla,bla,bla => bla bla bla
a:b:c => a..b..c
Sure just a sec
Input text example string
inputText = "Press [VoiceProx] to use proximity chat" where VoiceProx is a key that i use to get an actual button name from in settings
That comes from InputHandler.TryGetKeycode(string keybindName, out Keycode actualButtonCode)
I want to replace the bracket contents with whatever string contents it has
private string GetFormattedText(string inputText) {
if(inputText.Contains('[') && inputText.Contains(']')) {
//=> Replace keybinds with mapped button names
return formattedText;
}
else return inputText;
}
The first block is true even if theres '][' which I dont like
I still don't get it
example?
what should this return?
GetFormattedText("Press [VoiceProx] to use proximity chat");
the output would be "Press [V] to use proximity chat" where input would be "Press [VoiceProx] to use proximity chat"
why is V VoiceProx ?
VoiceProx is a key that I use to say "Hey inputHandler, what button does the user use for VoiceProx?"
PlayerSprint could be a code, inputhandler returns "LeftShift"
why check for the brackets at all? Just go through your entire list of mappings and text replace
it shoulg be done with Regex
I suppose that would work
I gon't get it anyways.
but why? You're doing a straight replace, regex is like using a golden hammer when a simple rock would do
what?
they probably need to do Regex.Replace()
So theres only 13 keybinds so the sample size is relatively small
this is only being called once when a message is loaded
Cant change binds while reading message
buddy, if he has the text "blah blah [REPLACE] blah" and he wants [REPLACE] to be something else, regex is a mega complicated solution when Replace will do
- take your input string
- loop over every possible mapping, and replace entries in the input string with the output mapping
- done
it's not complicated
That should probably work,
I dont believe any of the text could get replaced since the button codes are unique
exactly
$"Press [{GetKey("VoiceProx")}] to use proximity chat";
Could you use string interpolation for this?
I could maybe append a symbol in front like $ for inline string arguments
replace $ + code
private string GetFormattedText(string inputText)
{
string replacePattern = "[replaced]";
string replacedText = Regex.Replace(inputText, @"\[.*?\]", replacePattern);
return replacedText;
}
Id like to use that but these strings are defined in the inspector using a tool i made for non-programmer teammates
I cannot help you more, because I do not understand what you are trying to achieve
What do you think would happen for a string like "Press [LEFT] to move left and [RIGHT] to move right"?
"Press [replaced] to move left and [replaced] to move right"
what's wrong?
(?'replace'\[(?'key'[\w]*)\])
You then can match the Regex, use the group "key" for your dictionary etc and then replace the whole of the replace group
Hello! I assume this is a coding issue but I could be wrong. I coded a movement system for my 2D game. I made a map but whenever I press S to move my character, he just goes through the floor rather than walking "on it". What could the issue be?
you probably move it with it's transform
can you show code?
Sure, I also used the Unity Input Actions movement package too.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private Vector2 movement;
private Rigidbody2D rb;
private void Awake() {
rb = GetComponent<Rigidbody2D>();
}
private void OnMovement (InputValue value) {
movement = value.Get<Vector2>();
}
private void FixedUpdate() {
rb.MovePosition(rb.position + movement * Time.fixedDeltaTime);
}
}
!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.
Do you want me to send the hastebin.com file over with my code in it?
second variant.
oh wait
no
I mean with 3 `
public class PlayerMovement : MonoBehaviour
{
private Vector2 movement;
private Rigidbody2D rb;
private void Awake() {
rb = GetComponent<Rigidbody2D>();
}
private void OnMovement (InputValue value) {
movement = value.Get<Vector2>();
}
private void FixedUpdate() {
rb.MovePosition(rb.position + movement * Time.fixedDeltaTime);
}
}
do both your character and the floor have non-trigger colliders? @sharp oak
Yes
can you show them in Inspector?
Unless the difference is the issue. The floor has a Box Collider and the character has a Box Colldier 2D.
Also, yes, let me do that.
Okay I basically went with @mossy snow solution
private string GetFormattedText(string inputText) {
// Format text only if potential bracket pairs detected
if(inputText.Contains('[') && inputText.Contains(']')) {
string formattedText = inputText;
// Replace any key codes contained within square brackets
foreach(string keybindName in System.Enum.GetNames(typeof(KeybindMnk))) {
formattedText = formattedText.Replace("["+keybindName+"]",
"["+InputHandler.GetKeyCode(System.Enum.Parse<KeybindMnk>(keybindName)).ToString()+"]");
}
return formattedText;
}
else return inputText;
}
InputHandler.GetKeyCode(KeybindMnk keybind) is where the true button name comes from
I included brackets in the replace.
Not the most elegant solution but it seems to work
Its not called rapidly and the input size is never huge
I wonder if that's the issue.
that's not the most elegant, that's the least elegant solution 
what if you make'em both 2D (that's 2D game, right?)
Well, I made the map 3D but am trying to play it 2D.
Which probably wasn't too smart lol
you still those unnecessary bracket checks, and made it harder to read
private string GetFormattedText(string inputText) {
foreach (var binding in Enum.GetNames(typeof(KeybindMnk)).Select(kb => $"[{kb}]")) {
var replacement = "$[{InputHandler.GetKeyCode(System.Enum.Parse<KeybindMnk>(keybindName)).ToString()}]";
inputText = inputText.Replace(binding, replacement);
}
return inputText;
}```
yeah, it probably wasn't
I had watched a video and in the video the person had said that you could make me the map 3D but still make the game 2D
Is there any way for me to change the map to 2D without having to rebuild the entire thing?
If I understand this correctly, it would also replace keycodes that match but are outside of brackets?
you can, you just have to be careful. 2d colliders use the 2d physics system. 3d colliders use the 3d physics system. Both arenβt compatible with each other since they each have their own implementations
no, because brackets are added around each keybind
You can keep everything with 3d colliders. Or keep everything with 2d colliders
if you want them to interact with each other, they have to use the same type
But if I use 2D colliders on the 3D floor, I can't change it on the Z Axis, which means it won't cover the entire floor?
Thanks @mossy snow, you're getting a promotion
can you show a screenshot of your scene? itβs a bit difficult for me to visualize the issue you are having. Youβll have to have a 3d collider if you want it to interact with a 3d floor
I have a 3D map with a 2D character. And whenever I go into the camera and press play, he will go straight through the floor.
give him a 3d collider
In the component section is it called 3D collider or Box Collider?
box collider
theyβll also need a 3d rigidbody instead of the 2d rb
which should just be called Rigidbody
If you're working in 3d, the physics components need to be non 2d.
Worth noting that if you have bumps on the ground, a box collider can easily get stopped by them because it's not rounded at the bottom, so it won't slide over them easily.
But in a flat game a box is super efficient for sure.
Well in doing of that, my character fell straight through the floor and now I have a ton of errors. Since my movement code was set to RG2
does the floor have a collider as well thatβs 3d?
Youβll have to update your code to reflect your change
show the inspector of the floor and the player
I cannot play unless I fix the errors.
I do apologize to you guys, I don't have much knowledge have this stuff.
You probably need to reassign the rb variable of the 'PlayerMovement' script in the inspector
That's what I thought, but that option is greyed out
I would probably just disable the script for now. Is the object falling through the ground still?
wdym it's greyed out? π€
Normally you would put Rigidbody2D in the script then drag the Rigidbody2D into the settings of the script in the Inspector. But since I don't have a Rigidbody2D, I don't know what the line of code is for the 3d version. And same with the Vector. It used to be Vector2 but that isn't working anymore.
I cannot tell. I can't press play to see if it falls through because I have all of the errors
can you show your code and what the inspector for the object looks like?
also the 3d rigidbody is literally just Rigidbody which you can clearly see in your previous screenshot that shows a rigidbody component and also has a convenient (?) button that takes you to the docs for it
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private Vector2 movement;
private Rigidbody2D rb;
private void Awake() {
rb = GetComponent<Rigidbody2D>();
}
private void OnMovement (InputValue value) {
movement = value.Get<Vector2>();
}
private void FixedUpdate() {
rb.MovePosition(rb.position + movement * Time.fixedDeltaTime);
}
}
well they are private so of course they won't appear in the inspector unless you serialize them using the SerializeField attribute
but also this object clearly does not have a Rigidbody2D on it so that is why you were getting the errors
Exactly, but whenever I change Rigidbody2D to just Rigidbody, I still get errors.
One of the errors says something about Vector2 being wrong.
well yes, MovePosition expects a Vector3 not a Vector2. you will need to create a Vector3 from the movement vector so you can put the Y axis into the Z axis
this is all beginner stuff, there are beginner unity courses on the unity !learn site if you are not familiar with this
π§βπ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
Yea, I will check this out and see if I can learn anything. Thank you guys for the assistance though
Besides that, unless the guide covers it, is there a way to completely change my map to 2D, or is the only way to do that to rebuild it?
@glossy basin @potent sleet sorry to disturb you but just wanted to say thank you for the guidance, the solution was IK now even when i turn the camera up it works nice
Glad you got it working
Hello there, I guess this is kind of a beginner question, but how can I use a coroutine on a class that derives from an abstract class of type ScriptableObject?
public class ChargeWeaponPreset : WeaponBase
I have this class, where I want to use something like StartCorotine(Coroutine()); but since the base class is of type Scriptable Object, I cant do that
This is my base class
public abstract class WeaponBase : ScriptableObject
A global coroutine manager may work? If you're using a singleton pattern to access it, it should be relatively straightforward.
I thought of that, but I cant think of how I could be calling StartCoroutine from inside the ChargeWeapon class
How can I let my manager know that it has to start that coroutine
you need a monobehavior to start the coroutine off the SO
So if you have a class that has a public static instance of MyClass that extends Monobehaviour, you'd just do MyClass.Instance.StartCoroutine
Then any SO can use the same GO
I guess I could use my weapon manager class to do that
If there's any chance you may need it for any other areas, it'll be better to separate it
Otherwise (as an example) your armour would need a separate one that's exactly the same, or call on your weapon manager for it.
Which makes no sense
sound like a great place for the command pattern here. leave the command base class handle the coroutine and just use them from anywhere.
Yup, I get your point
Interesting, I will take a look into that
check the one from Jason like the one I sent earlier today. You'll see how you can apply this specific case to it
and unbound these things from the code itself but just creating instance of the command and executing them. The execution is then handled outside of the class you want to call it from (Thecoroutine in this case) and run in your commands instead.
Sounds very over engineering for needing to call one method on a Monobehaviour xD
Is there anywhere I can learn how to get the stack trace from a crash dump file?
that's always up to the use case. we have no context on how reusable this needs to be here. could be
isnt there anyone to help me with creating a 3d steering wheel controller pls
Hello. I've got some issues with my character movement.
Currently using a fixed upate to move my character.
I have an issue where my character suddently stops moving then sort of teleports forward with a jittery movement.
You can see in the video from 0:03 - 0:04 seconds the player stops briefly then appears to teleport a bit in a jittery movement.
I've tried to enable interpolate but doesnt seem to fix the issues.
Help would be appreciated!
Here is my code and the video to show it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IsometricPlayerMovementController : MonoBehaviour
{
public float movementSpeed = 1f;
public LayerMask solidObjectsLayer;
public LayerMask interactableLayer;
IsometricCharacterRenderer isoRenderer;
//private PlayerInput playerInput;
private PlayerInputActions playerInputActions;
private Rigidbody2D rbody;
private void Awake()
{
rbody = GetComponent<Rigidbody2D>();
isoRenderer = GetComponentInChildren<IsometricCharacterRenderer>();
//playerInput = GetComponent<PlayerInput>();
playerInputActions = new PlayerInputActions();
playerInputActions.Player_World.Enable();
}
// Update is called once per frame
void FixedUpdate()
{
Vector2 currentPos = rbody.position;
Vector2 inputVector = playerInputActions.Player_World.Movement.ReadValue<Vector2>();
inputVector.y = inputVector.y/2;
/*
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
//fixes diagonal movement on isometric scene
if(horizontalInput != 0 && verticalInput != 0)
{
verticalInput = verticalInput/2;
}
Vector2 inputVector = new Vector2(horizontalInput, verticalInput);
*/
inputVector = Vector2.ClampMagnitude(inputVector, 1);
Vector2 movement = inputVector * movementSpeed;
Vector2 newPos = currentPos + movement * Time.fixedDeltaTime;
isoRenderer.SetDirection(movement);
rbody.MovePosition(newPos);
}
}
!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.
you really should not be doing this
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
in FixedUpdate
would this go in update?
yes and cache the values for use in FixedUpdate
Well I hope that fixes the issue im having
oh wait no
thats the old unity input system
i commented that out actually
@knotty sun
The section looks commented out.
You are doing the same with the new input system there
indeed, sorry I missed that, same applies for new input system though
So what specificlaly should i replace and put in update?
Vector2 inputVector = playerInputActions.Player_World.Movement.ReadValue<Vector2>();
inputVector.y = inputVector.y/2;
inputVector = Vector2.ClampMagnitude(inputVector, 1);
Vector2 movement = inputVector * movementSpeed;
Vector2 newPos = currentPos + movement * Time.fixedDeltaTime;
this entire part?
The hiccup honestly looks like low frame rates where a teleport occurred due to fixed update occurring more than once.
Vector2 inputVector, cache this globally, set the value in Update
and use it in FixedUpdate
Projected path and position looks correct.
how would i fix that?
its honestly getting annoying cuase it def occurs more than once
Not sure what there is to fix. Profile your application and see if it's really a delay there.
There is
I ran the build and the issue still persists
fixedupdate can occur 0 to many times per frame. Usually use for physics based stuff. Any input might not be read here.
I had thought it would be an editor issue so I ran several builds
But still has this issue
I think the teleporting is the concern here rather than input lag.
Yeah.
I just cant seem to fix that random stop and then teleporting foward outta nowhere
it might still be linked. Does it teleport without any inputs?
it would be okay if it happens once, but it happens like once every 10 seconds? sometimes more
It should not be more than 50 times per second unless you change the settings.
That sounds like garbage collection, but without playing with your project I couldn't say for certain
I'd be more than happy to compile my project and send a zip file
for you to play around
@wind palm
This things been driving me nuts as I've been trying to fix a lotof things
Yeah, I don't run .exe files from discord
Turning interlpolate on and off/ messing with the physics stuff
Not that I think you're up to no good.
Oh.... welp
Profiling is the best way to see where the issue is.
Between 3 to 4 in the video, the character makes a slight jump. This likely occurs because draw frames were missed but physics frames still accounted for the delay (teleport). You could either not move accurately and in Update with some max distance threshold or accurately as you've got it with a teleport visually shown. This implies that there is really a frame delay. Use the profiler to ensure that's the issue.
Is there a way I can share the profiling results?
Not really sure how to read the profiling results
But I do notice that whenever the teleport issue occurs theres a spiek of some sort
There are tons of guides online that'll do a better job than a text based chat
Not sure if this helps though
But it occurs at 0:01 - 0:02
It looks like the garbage collector
If it's the dark green mostly
Looks like it on my phone.
You need to be careful with allocations.
Agreed, looks like GC collection
is using public dynamic Execute(){} when using the Command Pattern system bad practice if I want to return a variable to the commands caller?
I suggest you enabling deep profile and track down where the excesive GC is happening
Do not use dynamic in game development
Do you know why and what to replace it with in that case? to me this just seems like the cleanest way to return data for the command pattern guidelines in particular.
since when did unity even support the dynamic keyword?
use delegates
your command is a leaky abstraction if the caller is getting data from it, so technically a misuse here
replace with object casts if you cant resolve types at compile time
Dynamic is extremely slow. The C# compiler does not know what it is at compile time so has to figure it out as it goes. Which is clearly not good.
It's like me being you a piece of paper with random words and telling you to work it out, and you cannot do anything else until you know what it means.
dynamic has roughly same performance as reflection
dynamic is also not supported on some platforms that don't allow code jitting, that's the main reason to avoid here
and not "get meta once reuse later" but do it all over at every call performance
I mean that too I guess, but performance is key where a single line can cause your game to reduce in frames.
i see
Gives you less leg room to do other graphical "stuff".
in what way would I be using delegate by the way? like a public delegate int Execute(){} or something?
It entirely depends what data you're retrieving
If you have a ICommand interface, that would be so much better.
isnt the command pattern design all about the paramaters of the Execute method being empty though? and even if you would isnt it impossible to store a refrence as a class variable?
and yes I am using an ICommand interface, which all commands derive from
object b = new object();
Action a = () => {
int i = 5;
object obj = b;
print(obj);
}
is this a command?
but that would pass by reference not by value right?
only structs are passed by value
class Command<T>
{
private Func<T> del;
public Command(Func<T> del)
{
this.del = del;
}
public T Execute() => del?.Invoke();
}
Command<int> icmd = new Command<int>( () =>
{
MySystem ms = GetSystem<MySystem>();
float time = Time.time;
ms.PrintTimeBetweenCommandCreationAndExecution(time, Time.time);
});
is this close to what command pattern does?
Hi, I created a simple tool for mass renaming stuff but the problem is that it adds a 1 for each selected object.
Is there a way to prevent it from running for each selected object or do I have to write a different piece of code?
using UnityEditor;
using UnityEngine;
namespace Assets.NNR.Editor
{
public class MultiObjectRename
{
[MenuItem("GameObject/Rename Selected Objects", false, 0)]
private static void RenameSelectedObjects()
{
int objectCount = Selection.objects.Length;
if (objectCount < 2)
return;
Undo.RecordObjects(Selection.objects, "Multi Object Rename");
for (int i = 1; i < objectCount; i++)
{
GameObject selectedObject = Selection.objects[i] as GameObject;
if (selectedObject == null) continue;
selectedObject.name = Selection.objects[0].name + " " + (i + 1);
}
Selection.objects[0].name += " 1";
}
}
}
What would also be nice is opening up a dialog where you could enter a name but I wasn't able to figure out how to do that :/
forgot to send a picture of the result
Keep a copy of the original name and add the value to the end.
dont really know what you are asking of me here but I suppose it would be? although this does seem a bit hacky.
what's the point of storing the original name if I am not changing it till the very last line of the code?
for loop starts from 1, not 0
Assuming the name of the object selected is simply concatenating numbers to itself
purpose of this tool is mass renaming objects, it should look like this:
Plant Slot 1
Plant Slot 2
Plant Slot 3
etc.
you tried using dynamic, closure may be hackier than hundreds of command classes manually typed out, but its flexible
and you can use some factory if you need reusable commands
or you can mix the two, and have a generic command with a closure in it
I suppose will consider that then, although I dont imagine it being that clean in my specific use case as many enemies will be using the same command/action most likely. thanks for the help though I will definitely look into that.
I sent a copy of the build to my partner
He has no issue walking for 10minutes
He also had his profiler on and we didnt see any spikes
You haven't explained what's going on (can be determined by logging) but I'm assuming the function is occurring x times for every object selected, the last line adds 1 x amount of times. Then you've got one final rename that adds the index to the end.
It's highly dependent on pc specs etc.
Your issue is GC though.
You need to look into it.
Where the final name is that of the object at index 0 with an extra index numeric that you're concatenating.
Just save the original unnumbered name in a variable instead of reading it from the first object
Well technically if the issue is GC, wouldnt he also have the same problem?
He walked around for 10min and we couldnt find any issue
GC wouldnt just happen jsut to my pc right?
I did explain what happens.
For each selected object there is an extra 1 added before the final index because the function runs for each selected object.
I am asking if it's possible to run this function only once no matter how many selected objects there are.
It's highly dependent on the pc. GC happens in everyone's pc. But everyone's pc handles stuff differently. If you both ran a benchmark test you'd get different results too
chat gpt did that, the issue with that approach is that you can't change the value of the first object at all(I want it to end up as Item 1 not just Item) because you'd end up with the same issue I had
Perhaps theirs is just faster
Howd you suggest I fix it ? Did a lot of google searches to no avail π
There is no just 1 answer
For instance if you're using raycasts make sure you're using the nonalloc versions.
Garbage Collection happens if you're allocating and freeing memory (no longer referencing memory). Depending on computer/device hardware, you may or may not feel the impact. It's likely there though if you're both running the same application.
Arrays can be expensive too if used improperly.
No raycasts nor arrays have been usen so far
Only arrays for direcitonal facing
Then you've got issues with other elements in your code
static arrays
Static arrays are ok as look as you're not recreating them
Theres really only one other script that is being used to sort isometric sorting
If I did new int[1024] every update it'll have an effect
Nah we arent recreating them. Theyre just used to store the directions the player will face
this is kind of a workaround but not really because it requires you to add a 1 at the end of the first selected object(Item 1 instead of Item):
https://gdl.space/nayoqozare.cs
Clearly something is happening for GC to trigger
I'm on mobile and am assuming GC was kicking a fuss.
I don't understand what you mean by you can't change the first at all
You can do whatever you want
if you do change the value of the first selected object it'll just do the same thing my code did
Wrong
you'll end up with Item 1 1 1 1 1 2
Not if you actually save the unnumbered string in a variable that is unrelated to the object
And reuse it
how can I do that tho?
If I do it inside of that function it'll just get called for each object and I'll end up with the same thing that I have rn
ik what string interpolation is and how to use it, I don't see how that'll solve my problem
Yeah I know that too but its kinda hard to find out π
If the function is called for each item, you wouldn't need the for loop. Just a variable.
Any specific way to figure it out?
$"{originalName} {n}"
Without ever changing the originalName variable
and when do you store a value into the originalName?
You'll have to go through your code.
if you do it inside of the Rename Objects function it'll get called for each object and you'll end up with the same thing I have rn
not sure you can access the object which it is currently being ran for, let me check
You need to keep it separate from the display name
You know why you've got a bunch of ones there right? Not a trick question. It's because the function is concatenating one a bunch of time to element 0.
yes, pretty much what I've been saying this whole time, each time the function is called it adds a 1 to the original object's name for each selected object.
I've been trying to avoid that this whole time but idk how(keep in mind I still wanna rename the first selected object by adding a 1 to the end of it's name)
That isn't the issue though. Issue is that somewhere along the line, the for or if statement actually becomes valid and concatenates the name of the first element (which had a bunch of ones) plus index to each element.
I give up.
ok, I'll comment the whole for loop and end up with the same thing
here:
it's not the for loop that's causing the issue with the said approach
I am not entirely sure what you mean by display name and keeping it separate from that
Δ° need a 3d steering wheel controller script but i dont know how to make it the AI and YouTube cant help me
Can you help me doing it
before you make it AI, do you have a script that works based on your input?
please @ me if you have any other ideas
what are u even trying to do, the script you posted does what its told to
Δ° can only rotate my steering wheel when i presses a key to the left and when pressed d key to the right
I am aware of that, I am asking how to edit it in a way to do something else
i didnt see the original problem, its far up
This is all i can do but i need returning steering wheel and Max rotation angle etc
Like ETS 2 game
The first one I sent renames all the objects with additional 1s for each selected object.
I've made a workaround which does work but requires you to add the 1 to the end of the 1st object's name(I'll reply to that message).
I am asking if it's possible to run the said function only once no matter how many objects are selected or have some other workaround which doesn't require you to add a 1 to the end of the first object's name.
In case you missed it, it's an editor script which you access with the right click menu:
your steering wheel should go towards its max rotation from provided input. your input should work independently from your steeling wheel. Then you can swap out the input and give whatever AI input (like the AI gives vector3.right if it wants to go right for example).
All you need is like:
for (int i < plantBar.transform.childCount) {
plantBar.GetChild(i).name = $"Plant Slot {i}";
}``` no?
honestly the way u explained this doesnt even say what goal u are trying to achieve.
doesn't require you to add a 1 to the end of the first object's name
literally nothing requires u to do this..?
I don't want it to be called item, it is a script which is supposed to work with any name you input as the name of the original object.
At first, I wanted to have a dialog that would accept a string as an input for the base name but I couldn't figure out how to do that so I settled with this.
can you explain the actual goal? because everything im reading seems like im missing some massive context. Without this context, it seems like u just dont know how basic c# works or loops
There's not really a way to do this in general without trying to parse the "unnumbered" name from the first element, because it's impossible to tell if a number in the is from doing this code or just manually placed or something
if you don't add 1 to the end of the first object's name with this approach it'll end up like this:
Item
Ite2
Ite3
.
.
.
You have to be smarter about parsing the name
You can't just assume the name has a number or that the last character is a number or something
Your code would have to check
I am well aware of that, the problem is that at the very end of what you are suggesting I'd have to change that object's name to Item 1 from Item and end up with the exact same thing
im probably missing too much context, this sounds like a complete beginner problem to me where u just use an if statement to check if its 1
I tried doing that but wasn't able to find proper docs for it
No? Why? All you need to do is write code to try to parse the "plain" name from the name of the first object. Once you have that it's the simple for loop
Basically that just means looking for and removing any numerical characters and whitespace from the end
sure, and if the base name is missing 1 at the end I want to add it, therefore requiring me to edit it's name and ending up with 1 1 1 1 :/
You write the code like this
And replace the hard coded string for your parsed object name
Without the number
As long as you do this when parsing the name you're good
Sounds to me like it's just a matter of parsing the thing and removing any numerical character and going from there.
what if the base name has the numeric value at the end of it's name?
Plant Type 12 for example.