#archived-code-general
1 messages Β· Page 85 of 1
It's just if its within a certain range, it can shoot the player.
Side note, use ForceMode.Impulse instead of multiplying with some crazy number like 100
what is inRangeFire how's it related to movement though
It isn't I'm just posting more bits of code, I'm just throwing things that could possibly cause weird stuff in the moving code.
you'd have to debug your if conditions make sure none of them are running together
They aren't, I did that.
I did the debug.log and made different ones to make sure it wouldn't trigger. It just constantly moves regardless of state.
Would ResetPath() possibly work to stop it?
show code with the debugs
if (distanceFromPlayer >= 35)
{
spiderMesh.SetDestination(spiderMesh.transform.position);
inRangeFire = false;
Debug.Log("working");
}
else if(distanceFromPlayer<35 && distanceFromPlayer >= 20)
{
spiderMesh.SetDestination(player.position);
inRangeFire = false;
Debug.Log("Called");
}
else if(distanceFromPlayer <20 && distanceFromPlayer >= 15)
{
spiderMesh.SetDestination(player.position);
transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
inRangeFire = true;
Debug.Log("initiated");
}
else
{
spiderMesh.SetDestination(spiderMesh.transform.position);
transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
inRangeFire = true;
Debug.Log("Last");
}
Because no one saw my message on the the other channel so I waited a bit and posted it here
I'm 70/30 that there's a rule against doing that.
ok well crossposting isn't allowed
which Debug is being called when is suposed to stop
"Working" when it is outside the 35 unit radius and "Last" when it is too close.
So effectively the spider needs to be stopped when x>=35 or... when x<15
so it does run but does not stop even with Setting destination to itself ?
Correct.
Well
It doesn't move the player
It kind of just... zigzags a bit on the ground
a dirty fix but you can try set agent speed to 0 when in those if conditions
normally setting destination to itself works for me .
Okay... could using ResetPath() also be an option for stopping it?
you can try
isStopped = true
resetpath()
I never used it
So when dose it not count as cross posting
when you remove your post from the original channel
ok cool lmk if u fix it
Hey ya'll can I ask a question
That's why this is here.
Aha, cool
So I have a script that controls the rotation of a turret
and I'm trying to get the state of the rotation from the turret, but whenever I use Transform.Rotation, it throws an error saying its not defined for Transform
How do I get that rotation?
ah
neither is Transform unless you're making a separate reference other than itself
nah it's just a special propriety unity made for certain classes
any monobehavior has transform prop because it always belongs on a gameObject
every gameObject has transform and vice versa
Hey all ... I am trying to remember what is the name of this pattern:
Example: if (_lastDeviceUsed.displayName is "Mouse" or "Keyboard" or "")
Does anyone know? π
navmesh.isEnabled = true (or false).
you're disabling the whole navmesh just to stopp 1 agent
Stopping the one agent.
I know but still seems overkill
something else is wrong
you shouldn't have to do that
I renable it afterward.
It works fine.
if (distanceFromPlayer >= 35)
{
spiderMesh.enabled =false;
inRangeFire = false;
Debug.Log("working");
}
else if(distanceFromPlayer<35 && distanceFromPlayer >= 20)
{
spiderMesh.enabled =true;
spiderMesh.SetDestination(player.position);
inRangeFire = false;
Debug.Log("Called");
}
else if(distanceFromPlayer <20 && distanceFromPlayer >= 15)
{
spiderMesh.enabled = true;
spiderMesh.SetDestination(player.position);
transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
inRangeFire = true;
Debug.Log("initiated");
}
else
{
spiderMesh.enabled = false;
transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
inRangeFire = true;
Debug.Log("Last");
}
Hey if it works, that's all it matters, But I would still look into why it had to be done
I will.
did agent.Speed = 0 not work tho @pearl swallow
yeah it's odd then something is overriding it
Though I'm wondering if it may be because of the terrain not being flat?
But Navmesh isn't a collider.
Hey ... anyone know how to read vertex color in a C# script? I need to know the color of a specific vertex.
I already have a handle on the vert
as Vector3
nah , really this shouldn't be an issue . Something else is going on tbh
you can debug things like NavMeshAgent.destination
to check were they were actually going
also things like hasPath etc.
I'll tweak it later. I'm just happy it functions.
ok so I have this code
{
Window.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
public void OnPointerClick(PointerEventData eventData)
{
if (Opener == true && Window.active == false)
{
Debug.Log("frund");
compinfo.HowManyScreensUp++;
Window.SetActive(true);
Window.SendMessage("Loading");
}
else if (Opener == false && Window.active == true)
{
compinfo.HowManyScreensUp--;
Window.SetActive(false);
}
}
}```
i put it on an object and duplicated the object three times.
it works for the first two objects, and yet...
How do you have it be organized in opening up?
Is it an array or something?
err, i just put the script on each rawimage and pluged whatever game object i want opened into window in the inspector
Is the last one a button or something?
nope, all three of them are rawimages
And the 3rd one is connected properly?
yup, in fact can switch out the game object I have in window and the first and second one will still activate whatever is in the window varible but the third still doesn't
when running my game, it suddenly freezes and i have to force close unity. I debugged myself into knowing where it freezes. There is this function i call on button click. The first time i call it, everything is fine and it does what its supposed to do. The second time tho it freezes the whole thing. In the script there are a few debug points. when it freezes, it doesn't even print the first one. so im guessing something is going wrong when i call the method?
{
Debug.Log("0");
objectsToHide.SetActive(false);
objectsToHideButtons.SetActive(true);
Debug.Log("1");
do
{
int rndNameIndex = Random.Range(0, names.Length);
} while (rndNameIndex == previousRandomName);
previousRandomName = rndNameIndex;
Debug.Log("2");
textDisplayName.GetComponent<Text>().text = names[rndNameIndex];
Debug.Log("3");
}```
Hi, I have an assortment of points on the XY plane, and I would like to be able to draw a web between the points. Does anyone have any idea how to do this properly?
currently my code looks like this:
private void OnDrawGizmos() {
List<GameObject> drawn = new List<GameObject>();
for (int i = 0; i < _points.Count; i++) {
for (int j = i + 1; j < _points.Count && !drawn.Contains(_points[j]); ++j) {
Gizmos.DrawLine(_points[j].transform.position, _points[i].transform.position) ;
drawn.Add(_points[j]);
}
}
}```
So you want to connect nearby points together?
sounds like you need to make a maximally connected planar graph
to use a bunch of big words
i.e. you have as many connections as possible, but no two connections cross
sounds like its gonna take more time than I'm willing to spend rn lol
It's non-trivial
It's easy if you have a graph library. I did find one of those for a game jam a few months ago
it wasn't the worst to set up
What look you are looking for ? Can you choose the position of the point ? Do you really need that no line cross ? What are you trying to represent ? Is it a 3D viewer ?
It's mostly to visualize an algorithm I wrote which uses Divide and Conquer to find the pair of points with the smallest distance between them. Ideally I would want something like this:
I only want them to connect to reasonably adjacent points
@main token For each node, do a raycast within a limited distance towards each other node.
you could approximate this by adding colliders each time you link up two nodes π€
wdym, like checking intersecting colliders?
yeah, you'd shoot a raycast to see if the path is clear
it'd be an approximation of an algorithm to generate a planar graph
how would that be done in practice? Like raycasting towards a certain object, then comparing the object hit to the target?
hey if it works, it works
In mathematics and computational geometry, a Delaunay triangulation (also known as a Delone triangulation) for a given set P of discrete points in a general position is a triangulation DT(P) such that no point in P is inside the circumcircle of any triangle in DT(P). Delaunay triangulations maximize the minimum of all the angles of the triangle...
relevant concept
I remember seeing someone post a library for this on the unity forums a few years ago
a Delaunay triangulation avoids thin triangles
I would just do a POV graph (each node raycasts towards each other node), keeping track of all connections for each node. Then discarding all but the shortest connections and drawing them. It's naive and inefficient, but super simple to implement.
(POV: points of visibility)
Actually you don't need to raycast even
small question: How do you deal with properties in a Editor / Inspector script? How would I trigger certain functions after manually changing a public variable in the inspector?
The simplest way is OnValidate
the fancy way is a custom editor or a 3rd party plugin like this:
https://dbrizov.github.io/na-docs/attributes/meta_attributes/on_value_changed.html
Thanks. OnValidate() runs everytime any public property changed? Would there then be a way of knowing what value changed? Trying to wrap my head around how to implement it; Im not used to making extensive editor scripts π
The NaughtyAttributes plugin seems more handy prob
anyone?
Thanks @leaden ice always on poin!!
Your loop is infinite. The rndNameIndex you create inside the loop isn't the same as the rndNameIndex you check in the condition. Thus, the condition result will never change
Your code editor probably tells you that the variable inside the loop is unused, its name will have a faded color, compared to other variable names, as well as a suggestion to remove it
oh yea youre right. it doesnt say remove, but it is grayed out. Thanks
Late reply but I have used this one, its decent
https://github.com/nol1fe/delaunator-sharp
Question: I'm trying to make a custom editor where I can manipulate a (cubic) bezier curve
so far so good:
For the next step I'd like to add Nodes for P1 and P2 (the two tangents), so I can drag and drop them with the mouse.. Anybody any idea on how I'd go about that? Some terms to steer me in the right direction?
This can come handy https://docs.unity3d.com/ScriptReference/Handles.PositionHandle.html
rotate the 3D handle so that it seems 2d, and draw it on the inspector rather then in the scene view?
Hi, I'm working with configurable joints, and I'm trying to get the local position of an anchor through code. .targetPosition doesn't seem to do the trick, what can I use instead?
.anchor returns the local position unscaled and unrotated, it seems
How do I paste code here?
!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.
Thanks
Why are you doing a bezier ?
Is it for a spline editor ?
[CustomEditor(typeof(T_Bezier2))]
public class T_Bezier : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
Rect rect = GUILayoutUtility.GetRect(10, 1000, 200, 200);
T_Bezier2 bez = (T_Bezier2)target;
GUI.BeginClip(rect);
Vector3 positionHandlesPosition = Handles.PositionHandle(new Vector3(200,200,0), Quaternion.Euler(new Vector3(0,0,0)) );
Handles.DrawAAPolyLine(Texture2D.whiteTexture, 5, bez.points);
GUI.EndClip();
}
}
this gives me null errors when I try to create a position handle in the Inspector, anyone any idea?
I'm using calculated bezier curves in my code, and I'd like a visual way of editing them, rather then just using the numbers
OnSceneGUI
yeah i need it in the inspector. Looking into OnDrawGizmos!
someone pls help. There must be a way to get the local/world position of the anchor. right?
On draw gizmo is on the scene
ondrawgizmos is scene, not inspector
sry
ahh okok. Yeah I need to be able to move nodes by dragging them with the mouse. I suspect I just draw tiny cubes in OnInspectorGUI, but I need to register the mouse clicks and movements
What are you trying to do ? Doing this in the inspector seem unwell.
So P1 and P2 are the tangents, I would like to drag them in the visualization part, rather then having to set the numbers
parentTransform.TransformPoint(joint.anchor) worked
and btw the bezier curve drawn there is done in OnInspectorGUI with Handles.DrawAAPolyLine, it's not just Windows' paint π
What are you doing with your Bezier curve ?
I was actually looking into that. But you beat me to it π
Like, what is your purpose.
I use it to calculate some specific physics / velocity calculations for my own physics engine
Since when you need bezier curve for that ?
well, lets say Simulation of a physics engine lol.. Its neither here nor there, im really just trying to fix a inspector script π
Is there any reason why you would not use the scene view ?
Like what are you doing with it.
Is it interpolation ?
@solemn rune why don't you just use AnimationCurve? It's a cool 2D bezier curve editor, built in
But it'll be slow for a physics engine
use trigonometry if u can
can i use that as part of a custom editor script?
Oh I am, this part is just the visualization of the formulas
no custom editor required, even
Ahh ok, yeah I need the tangent positions etc for my formulas, cant use keys
how about curve.Evaluate()?
that just gives you the value at a specific point on the curve
iirc, animation curves store the tangents as slopes
can't you calculate it though, from that
You first need to have the curve
Yeah you prob could. But, I'm using quadratic and cubic beziers etc, already doing it in code etc
Plus, I like this part, learning about editor scripts and visualisation, it's a nice change of pace
I still do not know why you are trying to make a bezier in the inspector. It is not really made for that.
Well, in essence, using bezier calculations is a more flexible way of Lerping or Slerping something
the bezier in the editor is just the visualization of the bezier calculations used
Then you should try to convert your bezier curve into the animation curve editor
If you do not want to manipulate the point
But bezier curve are never used for Lerping
There are way to complex for that.
I use the bezier formulas to interpolate stuff.. and so far so good, especially since I do the calculations myself in script.. All I need is 3 or 4 Vec2s
the math is not That complex
It is not complex as the math, but as the performance.
but it would be really heavy if I did that multiple times per frame, and then having to look that up in an animation curve yeah
And unrequired flexibility
i mean, not for lerping, sure
but it's very common to do transitions with cubic bezier curves in, say, web browsers
It is like doing 3-4 lerp betwen 3-4 points
Pretty sure animator does not use bezier curve.
a simple quadratic bezier: position = (1.0f - t) * (1.0f - t) * p0 + 2.0f * (1.0f - t) * t * p1 + t * t * p2; It's not that heavy...
Granted I prob wouldnt use it in a shader or something, but in my use case it isnt impacting any performance at all. And, it gives me way more flexibility in interpolating
How can I create a field, to which I will be able to attach either a rigidbody or a articulation body?
Both inherit from Component
I don't want anything else to be attachable
custom editor script ?
I'd rather to avoid that. It's too much work for a simple task
it's not that much work really, you could just make a bool control which one can be inserted
hide the field depending on bool
yea, but that's a whole other class
I guess I'll just make 2 fields, like the people who made the spring joints that I'm using did...
IDK why I was trying to be smart
eh it's more to do with if you can find a simpler way to a problem why not take it
can please anyone send me a video that has script for 2d health and attack i couldn't find any that actualy works ?
where did you look ?
I seriously doubt there is one that doesn't work especially in tutorials on youtube
no it just that it isn't what i want like if they show what i need there is no link to code and if there is a link to code it isn't what i want
it's not going to be EXACTLY what you want
if it was, there would be no point in making a game, because it would already exist
not even close
just health and damage
i seriously doubt that you're doing something so incredibly unique that all existing reference material is useless
health and damage is basically just making a number go up and down
agree this is also incredibly basic for this channel and should be in #π»βcode-beginner
if we compare a value assign to a variable and instantiating an object, how many times more heavy is instantiating an object?
give an example .
wdym heavy ?
comparing and assigning local variables is basically free
instantinating is very very heavy
it's not a competition
that said, depends what you're comparing, if you're doing something like transform.position then that's an internal call and can be slow at times
when you do it a lot
Camera.main is another thing like that
I see
I was making a pool manager and thought, that's a lot of code to grab an object and store it, I started wondering if it's starting to be more slower than instantiating an object
depends how you grab it
singleton? basically free
GameObject.Find? probably better instantiate
but if you're running it once (or rarely), it doesn't matter anyway
unless you're doing it at least every frame you're good with whatever solution you come up with
so probably not worth it to worry about it much
yup, thanks I'm using singleton for the manager and not using slow methods like get components, or find, so yeah, it's decently optimized
singletons can be a bit much code, yes, but they are fast and very very cool
just remember that you should initialize it in Awake and call it in Start
and despite what documentation would lead you to believe, you can't actually initialize singletons in Awake, and call them from somewhere else in OnEnable, which, according to this
https://docs.unity3d.com/Manual/ExecutionOrder.html
should be possible.
In truth, OnEnable and Awake are called in order only on one object
Like
foreach (obj in objects)
{
obj.Awake();
obj.OnEnable();
}
or something like that
I'm saying it cuz it bit me in the ass once, and I didn't find the issue for a couple of hours...
Hi there. Im trying to pause my game using a gamepad as our only way of controlling the game. Ive been trying to set time.timeScale = 0 to pause our game but i realize that this makes it impossible to use the pause menu. Is there a way to circumvent this?
will keep it in mind, cause I feel it will happen to me too in the future, thanks for the infoo
This is an extremely annoying issue
what I did, is I had a PauseManager with a static bool isPaused, and all objects checked it
or all objects derived from PausableObject, registered themselves on the PauseManager, and PauseManager called Pause and Unpause on those objects
but that's a ton of effort
I think there is a way to keep UI going despite timescale being 0, but I don't remember how it went
I am not sure if there is a way to do it
I think there could be
I'm not sure if fixedTimeStep won't keep going, meaning FixedUpdate will keep getting called though
hmm okay. i appreciate your help
Does anyone know, why, if I do something like this
joint.connectedArticulationBody = default;
or
joint.connectedArticulationBody = null;
I get an error "A joint can't connect the body to itself." but when I do the same with joint.connectedBody, there is no error?
the articulation body does not turn to null when I check in the inspector after it was called
The way unity handles code is rather confusing. How do I get collisions to disable if I press a key?
that's a very vague statement
"the way unity handles code"
so you want to make an object stop colliding with anything when you push a key
Yes.
I say that because the errors are sometimes weird.
yes, errors are sometimes weird
you just need to disable its colliders, then
If you aren't using the new input system, then you'll just do something like this to get input
if (Input.GetKeyDown(KeyCode.F))
{
// ...
}
OK... I'll try that.
disabling colliders is like disabling any other behaviour: set the .enabled field of the behaviour to false
you can stick a list of colliders on a component with
public List<Collider> colliders;
and then iterate over all of them to turn them on and off
foreach (var collider in colliders)
collider.enabled = false;
Ah. That's what I was struggling with. Thanks.
hello, i have a problem with my 2d rigidbody jumping, tried separating the input and physics into Update and Fixedupdate but my jump height is still determined by the player's velocity, what i need is consistent jumps whenever i try to double jump https://gdl.space/zabobeqofe.cs
Try using ForceMode. Then you can choose whether or not to use velocity, mass, air friction, ect.
i tried using addforce
tried both with impulse and force but it doesn't work for some reason
Are there no more options?
not sure
Which part of the code is this? I'm on the link you sent.
so the double jump is the inconsistent one?
or is the first jump the problem
Is there any way to rename a word in all places, classes, properties, methods, etc.? jetbrains rider
For example StuffManager class, StuffType enum, _stuff field, stuff variable, DoStuff() method.
Replace Stuff/stuff with a new word
so the sooner you press the higher you go
rb.velocity = new Vector3(rb.velocity.x, doublejumpForce - rb.velocity.y);
why doesn't this just set the y velocity?
it sets your y velocity to doubleJumpForce minus your current y velocity
i tried to do something like rb.velocity -= rb.velocity.y
but ig that doesn't work?
Maybe try doubleJumpForce + rb.velocity.y.
yes, this would also be reasonable
it would make the second jump make you move faster than you were
hm
Or just add the force of a single jump to your y velocity.
but rb.velocity.y is a vector2 and JumpForce is a float
would that still work?
wdym
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
you already do this
just...do it again
that'll make both jumps equal
I haven't had to do it yet.
then do the double jump differently!
rb.velocity = new Vector2(rb.velocity.x, jumpForce + rb.velocity.y);
ah
why not just use doublejumpForce instead of jumpForce?
like if i want the doubleJump to be consistent but different height value than the jumpForce
sure
yep
use a different number
:/
double jump still the same
i feel like i need a way to completely reset the y velocity to 0 and then double jump
You could write the code like I did. It's not the right way of doing it, but its allows double jumps.
And triple, quadruple, and any other jumps that you might need.
And if you hold the jump button you continuously go upwards...
It's buggy, but it works.
well it can probably be fixed
Yes, I coded it like this for a deliberate glitch in the game I'm making.
ah nice
tried doing this in the double jump couroutine but it also didn't work :/
rb.velocity = new Vector2(rb.velocity.x, 0);
rb.velocity = new Vector2(rb.velocity.x, doublejumpForce);
?
This.
yes where did you see/get that error
The debug log.
uhh
?
im confused, you talking about my code or yours?
yep
Everything in my code is working, it's just displaying the warning.
you probably deleted a script that you had assigned on a prefab or something
basically nothing
(i think that's what it is)
Probably correct, but how do I stop it?
check the prefabs that you made to try and find a missing script on the script component
how would I count these squares on tilemap by a certain amount ? the white dots
As far as I know, all the prefabs are assigned.
wait
check your c# script
it should say public class (the c# script name)
or else the script won't work
the class definition of a script needs to be the same as it's name
How can I easily do an OnComponentAdd and OnComponentRemove inside a component?
I want to set the layer of the object to something when a component is added, and changed to default when it is removed
OnDisable/ OnEnable
How can I get the contact position for the collider (onTrigger)?
Doesnt the collider passed in contain the transform which has the position so like other.transform.posistion I dont know for sure.
I want the exact spot/spots of a collision(trigger), not the position of the other collider.
OnTriggerEnter doesn't provide contact points, because there is no contact
Just an overlap
Can I somehow get the overlap area and/or position?
I think I can get bounds of two colliders and find an overlap myself, but is there a more efficient way?
What is the purpose for this?
Are you trying to depenetrate two colliders?
Regardless of the purpose, this should give you exactly what you need
hay is this a good way to iterate through a list of targets to find which is the closest?
Hello there, has somebody used UniTask before? I am having some issues with it
I feel like what I did works but could be improved so I wanted to ask here
My uni task state is always pending, so whenever a new task is added, it stays there
Gotta share some code.
So, here is my infinite generator code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have literally 0 knowledge on both task and UniTask, I just followed some guides, so any help would be appreciated π
here is the async function that waits for generating the chunks
and here is the function that generates the actual chunk
What's dataJobHandle here?
I'd also be extra careful with calling async methods from update.
data job handle is a JobHandle I use for generating world data, here is the code of that
On the first line of this code, on the ternary condition
Wait. It's waiting while it is finished. Is that waht you want?
The task would only complete when this job is runing.
I assumed I had to put the job handle status on the wait while in order to run the task, is it wrong?
Wait while implies that when the condition is true, you wait.
do you guys know any thing about lag compensation?
How would I aproach this instead of using Update?
thanks
I'm not sure update is the issue here. I just mentioned that you should be careful to make sure that your tasks don't snowball over several frames.
I actually thing this may be the case
the profiler shows me an INSANE amount of calls to the async
Okay, well, you could make clear logic that would track if a task is currently running, and avoid starting a new one.
I guess this is also the reason I get some garbage from time to time
I guess this can be held using a simple boolean, right?
Yes. You could set refreshing bool to true when you start refreshing and set it to false when it's done.
Question: In a script, I'm unable to reference one type of interface, and yet I'm able to reference another type of interface defined under the same conditions and namespace. Does anyone have any idea why?
Not without seeing your code/errors
I'm getting this error: The type or namespace name 'IInteractable' could not be found (are you missing a using directive or an assembly reference?)
Just to be clear, you get this error in the ide?
Yes, correct, Visual Studio Code.
This looks like your class name is not the same as the inteface name
Ok, share the code where you define the interface and where you try to access it.
I'm able to reference this interface in question in another script, just not in this script for some reason.
Hmm, maybe you set a namespace for the interface and you are not using it in the other script?
It will make it so much easier for everyone if you just shared the relevant code
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Cleverous.VaultInventory
{
public interface IInteractable
{
Transform transform { get; }
void Interact();
}
}`
And the script where you try to access it?
`namespace Cleverous.VaultInventory
{
[RequireComponent(typeof(Collider))]
public class RuntimeItemProxy : NetworkBehaviour
{
...
public virtual void TryPickup(IUseInventory requestor)
{
IUseInventory inventory = null;
IInteractable interactable = null;
...`
I'm sorry, the script is quite long, so I've tried to abbreviate it.
Ok, seems okay I guess. Unless IInteractable is in a different assembly, it should work.
Don't ask to ask...
This is not the #π€βintroductions chanel. If you have a question, ask right away.
Also, I see that you're getting help in the other channel. Please don't cross post
sorry duley noted thank u @cosmic rain
I don't think it's in a different assembly, I'm not sure what I should even try to do ...
First of all,comment out everything causing a compile error, make sure your code is recompiled and try to reference the interface again.
Also, if the error only happens in VS code and not in unity, there's probably something wrong with your code editor.
OK, I appreciate the help, I'll look into that.
Also it goes without saying, but your code files all need to be in the Assets folder of your project.
I'm getting the error in Unity as well.
Yes, they're all in the Assets folder.
Ok, can you take take a screenshot of where the 2 files are located physically?
Are you making use of assembly definitions in your project perhaps?
https://www.youtube.com/watch?v=HYqOSkHI674
I'm watching this video, because I don't know what that is, lol.
Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP
In this video, you'll learn how to use Assembly Definitions to organize your code in Unity.
#Unity3D #UnityTutorial #GameDevelopment
π¨π» Join our community: https://discord.gg/NjjQ3BU
β€οΈ Support the channel: https://www.patreon.com/infalliblecode
My Favorite Unity Assets π―‡...
I'm making use of someone else's inventory project, so perhaps this is a question for them, I'll ask on their Discord.
@cosmic rain I appreciate your time and help so far. Thank you.
If they're using assembly definitions and one of the files in question enter that assembly, while the other one doesn't, it could be the cause of the issue.
@cosmic rain The answer is yes.
Well, then that's probably the problem.
@cosmic rain As a workaround, I guess I'll try to move this function over to another script, or something like that. Thank you for your help, you saved me a lot of headache.
I'd advice learning about assembly definitions properly instead. If you're gonna include them in your project, there might be other issues I'm the future.
OK, I really have no concept of what they are, so you're absolutely right.
I have two vectors - v1 and v2 and need to find the angle theta relative to the x-axis. How would I go about doing so? I current am just doing atan(v2.y-v1.y/v2.x-v1.x), but the angle is computed incorrectly when I'm in any quadrant other than the first one.
@smoky pikeatan2?
ooh thank you didn't know about that one
not being able to use the ?? operator on unity objects is a travesty
use ternary
yes ik. I'm just sad I have to do
get => _instance != null ? _instance : new();
```rather than
```cs
get => _instance ?? (_instance = new());
How would I integrate this with a Quaternion? I have the angle and am instantiating a line with that angle at a certain point: Quaternion.Euler(0f,0f,angle); but the angle of the lines seem to be instantiated in the 2nd quadrant
I find comparing game objects to bools gross
No clue. Someone else is gonna have to answer that
there's nothing different than comparing to null as far as i know
the bool is just doing the != null behind the scenes:3
are you trying to rotate a vector with a quaternion?
yes but gross (this is my opinion, I think it's too unclear, it's a totally valid way to do it)
I am instantiating a gameobject with the angle I just computed: Instantiate(gameObject, new Vector2(pos.x,pos.y), Quaternion.Euler(0f,0f,angle );
Why not ```cs
get => _instance ??= new();
try doing
GameObject o = Instantiate(gameObject, new Vector2(pos.x,pos.y), Quaternion.Identity;
o.transform.forward = Quaternion.Euler(0f, 0f, angle) * Vector3.forward;
because unity can't override the ?? operator
Don't use Monobehaviour objects?
also cool, I honestly didn't know you can do ??=
No i have to
this works for uity objects?
way easier access for peeps to modify the values of the singleton
no
No this does not.
I thought it does
https://github.com/microsoft/Microsoft.Unity.Analyzers/blob/main/doc/USP0001.md
If you use the == operator to compare a UnityEngine.Object to null, it will return true if the UnityEngine.Object is destroyed, even if the object itself isn't actually null. The ?? operator cannot be overridden in this way, and therefore behaves inconsistently with the == operator, because it checks for null in a different way.
Plus, I think internally, you can't access the constructor? It's also marked private?
I've never had a problem doing new GameObject()
also I realize what I told you to do would do nothing, I was assuming you had the quaternion you wanted @smoky pike
you need help getting the quaternion, right?
yes
and you're on a 2D plane, and want to make the object face that angle?
yep
did you get it working with atan2?
i got the angles which seem to be correct
try doing
transform.right = (Vector2)(Quaternion.Euler(0,0,angle) * Vector2.right)
off the top of my head I think that'll rotate the right vector to the correct angle
the transform for the instantiated gameobject correct?
yeah that works tysm for the help
This isn't really a coding question, but yayyy I have a null pointer to a gameobject, what do i do? I can't delete it. (the script error is because it's supposed to have a reference to that object)
Press clear in console
oh you mean it comes up when you press play
Pretty odd error. GameObjects on the backend are native C++ objects I'm pretty sure
are you using unsafe code?
nope!
In the editor
the gameobject is greyed out
so that likely has something to do with it
parts of unity have c# pointers, so maybe it's not in the c++ part lol
https://stackoverflow.com/a/68557338
Probably the error is due to the fact that you are destroying some prefab that is not unpacked, so not destroyable by the runtime GameObject.Destroy that is to destroy a cloned copy from the scene.
'PlayerMotor' does not contain a definition for 'Move' and no accessible extension method 'Move' accepting a first argument of type 'PlayerMotor' could be found. Please help. I don't understand a majority of these error messages.
Then you should be in beginner
nobody can help you without posting code either
Good point.
ok I fixed it.
I edited the scene file in notepad++ and found the broken gameObject (not that hard considering there's not many lol) and just deleted the text for it and now it's fine!
When finding the distance between a client and an enemy, I run the command every frame to detect distance, all that is changing is the enemies and clients position by very small increments, yet I get random extreme outliers like this (see distance from target). Any ideas on how I can fix this. Btw both the client and host are run from the same pc so I don't think its a lag problem. Help with this would be greatly appreciated.
For starters, looking at the code could be helpful
if(!IsHost){return;}
HostDistance = Vector3.Distance(NetworkManager.Singleton.ConnectedClients[0].PlayerObject.transform.position, Dalek.transform.position);
ClientDistance = Vector3.Distance(NetworkManager.Singleton.ConnectedClients[1].PlayerObject.transform.position, Dalek.transform.position);
if(HostDistance < ClientDistance)
{
Target = NetworkManager.Singleton.ConnectedClients[0].PlayerObject;
print("Distance from Target: " + HostDistance + "\n" + "Distance from Non-Target: " + ClientDistance + "\n" + "Target: " + "Host");
}
if(HostDistance > ClientDistance)
{
Target = NetworkManager.Singleton.ConnectedClients[1].PlayerObject;
print("Distance from Target: " + ClientDistance + "\n" + "Distance from Non-Target: " + HostDistance + "\n" + "Target: " + "Client");
}
```Run in update
I'd check if Dalek, ConnectedClients[0] and ConnectedClients[1] always refer to the same objects.
Yeah they are always referring to the same object
The only time they wouldnt be is if I was hosting the game via the build instead of through the editor.
Are you sure? Maybe print their names along the debug log?
If they are, then something's moving them to weird positions for a frame
According to your logs.
Yeah
I'll do that
rn the naming system is just auto assigned, 0 is always the host and 1,2,3 etc are always clients.
Does Transform.InverseTransformVector only change the representation of the vector or the vector gets changed instead?
Target: [Host] Name: 0
Distance from Target: 67.07581
Distance from Non-Target: 77.5272
Target: [Host] Name: 0
Distance from Target: 27.38524
Distance from Non-Target: 67.06821
Target: [Client] Name: 1
Distance from Target: 67.05099
Distance from Non-Target: 77.54034
Its still happening randomly, here is a new log that also shows names
What about Dalek?
Like the daleks distance from the players?
No. The object's name
Ah no, I am measuring the distance between the players and the dalek.
Yes, that why I'm asking
Here's how you log needs to look like to provide good debug info:
Distance from player0 to Dalek0: 3637
Distance from player1 to Dalek0: 3648
Okay I'll rewrite them in that format
Distance from player0(Host) to Dalek0: 8.965793
Distance from player1(Client) to Dalek0: 7.23741
Closest player is player1
Distance from player0(Host) to Dalek0: 8.914283
Distance from player1(Client) to Dalek0: 14.93916
Closest player is player0
Distance from player0(Host) to Dalek0: 9.003682
Distance from player1(Client) to Dalek0: 7.063987
Closest player is player1
Okay here is another extract from the logs using your formatting showing the randomly changing positions.
The dalek is a nav mesh agent so could it be that randomly tping it somewhere for a frame?
Okay. So at least it's clear that it's player1 position that jumps.
Yeah
I have noticed its only on the client
the client is run on a built version whereas the host is run through editor
thats the only difference I can think of
Did you try logging the same stuff on the actual client?
Or is on the client?
Or the host?
No its player authoritative
Idk I am not changing its position only it is through keyboard controls.
Ok, so outputting same logs on the client could help.
i cant see any visual change in the players position for a frame if thats what you mean.
Its only in the logs
1 frame could easily be missed by a human eye.
true
if I record it at 60fps and have the application set to 60fps it should capture every frame right?
then run through in a video editing software frame by frame
If you confirm via the log that the issue doesn't happen on the client, then it must be something about syncing positions between the client and the host.
yeah
Why go so far when you can just print logs on the client? Lol
I could have the player send their position to the host via an rpc rather than by the dalek checking the players position through its object on host side?
You're thinking about walk-arounds before you even understand the issue. That's not how debugging works.
I'm just getting a "NotServerException: ConnectedClients should only be accessed on server." error, which is understandable, can I give clients access?
What exactly throws that error?
I'm pretty sure its
HostDistance = Vector3.Distance(NetworkManager.Singleton.ConnectedClients[0].PlayerObject.transform.position, Dalek.transform.position);
ClientDistance = Vector3.Distance(NetworkManager.Singleton.ConnectedClients[1].PlayerObject.transform.position, Dalek.transform.position);
On the local client you should have an access to the player character directly. You don't need to reference it via the Network manager.
have found the fix, It works but only if nobody is in the pause menu.
I have it so that when you press tab the player movement script is temporarily disabled
and you mouse is unlocked from the screen
The pause menu has no connection to the dalek code
so idk why this is happening
Why would Dalek code matter at all? The issue was with the player position.
I agree
When you disable the movement controller, it either does something with the position itself or with what/how it syncs with the host.
That's what I can guess from the limited information available at least.
I'll send the code
void Update()
{
if(Input.GetKeyDown(KeyCode.Tab))
{
if(MouseStatus == "Enabled")
{
Cursor.lockState = CursorLockMode.None;
MouseStatus = "Disabled";
GetComponent<InputManager>().enabled = false;
}else if(MouseStatus == "Disabled" || MouseStatus == "GameOpenState" )
{
Cursor.lockState = CursorLockMode.Locked;
MouseStatus = "Enabled";
GetComponent<InputManager>().enabled = true;
}
}
}
Ok, and what does the InputManager do?
please replace string literals with consts
private PlayerInput playerInput;
private PlayerInput.OnFootActions onFoot;
private PlayerMotor motor;
private PlayerLook look;
void Awake()
{
playerInput = new PlayerInput();
onFoot = playerInput.OnFoot;
motor = GetComponent<PlayerMotor>();
look = GetComponent<PlayerLook>();
onFoot.Jump.performed += ctx => motor.Jump();
onFoot.Crouch.performed += ctx => motor.Crouch();
onFoot.Sprint.performed += ctx => motor.startSprint();
onFoot.Sprint.canceled += ctx => motor.endSprint();
}
void FixedUpdate()
{
motor.ProcessMove(onFoot.Movement.ReadValue<Vector2>());
}
private void LateUpdate()
{
look.ProcessLook(onFoot.Look.ReadValue<Vector2>());
}
private void OnEnable()
{
onFoot.Enable();
}
private void OnDisable()
{
onFoot.Disable();
}
Yeah, an enum would be suitable there.
one easy approach to solving similar situation is to keep a stack
or a counter
if its empty the thing is allowed to happen
every time some menu opens it either adds to counter or gets a "token" that it holds
other systems react to the stack being empty or having something, disabling themselves
solves a lot of issues like ui panel hirarchies, stacked input maps etc
It's kinda hard to figure out just from looking at the code, but there's probably something going on with your input(or how you consume it) when you enable/disable this script. I'd check the values passed into ProcessMove around the time the issue happens.
Incase it was using values from before it was disabled?
Something like that
I'll try disabling the input script instead of disabling the movement script itself
It'll do the same thing without halting calculations done by the movement system, which fixes another bug of how the player doesnt fall when in menu
I have a Vector3 in world space. And I have a Transform which I want to use for this Vector3 as world space meaning I want the vector to have the same rotation as the transform. How do I do it?
you have a direction vector?
transform already comes with transform.forward which is z+ in world space direction
The vector isn't a Vector3.forward but another vector like (-10f, 5f, 3,4f)
i never said Vector3.forward
Why did you mention transform.forward then
so your picture doesn't match your original description:
I have a Vector3 in world space. And I have a Transform which I want to use for this Vector3 as world space meaning I want the vector to have the same rotation as the transform. How do I do it?
That vector doesn't have the same rotation as the transform nor is it the same vector but in local space. But perhapsTransform.InverseTransformDirectionwill help you? https://docs.unity3d.com/ScriptReference/Transform.InverseTransformDirection.html
Transforms adirectionfrom world space to local space.
I'm want to get the position/positions of the penetration.
Ideally some coordinates of the yellow area and/or green point.
you're likely going to have to rig something up with computepenetration
What do you mean by "rig up"?
they mean code something using CompuitePenetration.
https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
I did check the docs, but I don't completely understand how it can solve the problem besides trying to check every point (with some spaces i guess) of the first collider. As far as I understand, ComputePenetration takes two colliders and a point, returns if colliders overlaps at this point.
just get a collision point and use that method to check if they're overlapping on the collision point?
just get a collision point
How?
Actually, my initial question was "how to get collision point(s) if the two colliders".
And as far as I understand, there are no build in method for it.
it returns you a vector
with the OnCollision method you can use collision.contacts
by which you offset the object so they dont overlap anymore
https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
https://docs.unity3d.com/ScriptReference/Collision.html
The contact points generated by the physics engine. You should avoid using this as it produces memory garbage. Use GetContact or GetContacts instead.
https://docs.unity3d.com/ScriptReference/Collision.GetContacts.html
Retrieves all contact points for this collision.
what should the green point represent?
I have colliders in the onTrigger. There are no contacts calculated for this type of overlaping.
is the trigger axis aligned?
if it is you do something like https://docs.unity3d.com/ScriptReference/Bounds.ClosestPoint.html on the centroid
can do something like it
couldn't you do OnTriggerEnter() then use other.ClosestPoint(transform.position)?
woo nice one
you gave bounds and they might not think there's an equivalent for a collider, which includes rotation.
wait @hollow hound is this 2D?
Point on the surface of the second collider that are in the overlap and is
- nearest to the origin
- or center of the overlapped surface line
Yes
It will give point outside the overlap. I need basically the same, but inside overlapped area
what? That doesn't give a point. Wait, that reply is weird.
So the OverlapPoint again brings us to the solution if the checking all points (with some spaces) of the collier, which is kinda working but seems way too inefficient and not precise.
OverlapCollider just gives the colliders that are overlapping with this collider, right?
What's the use case for this?
No, they can be with different angle, if I understand correctly what you are asking about.
Like are you:
- trying to draw something
- trying to calculate volume of overlapping area?
- trying to spawn something at contact points?
Etc
can you raycast from the centroid towards movement vector
i dont know if you can hit trigger, you should right?
Find a point of the hit of the hitbox to spawn there another entity.
General question would be: How to find point that is on the surface of area of the overlapping / of two colliders and nearest to the another given point. Preferably without iterating through points in the collider.
I would track the previous position of my object in FixedUpdate, then when the collision happens do a BoxCast for example from previous position to current
That will get you "contact points"
The thing is, there are no movement, trigger collision just spawns in place (but there can be in a general case)
if all fails my sleep deprived mind just came up with an idea to keep parallel physics world with kinematic/non kinematic colliders mirroring objects and triggers to get collision points
The trigger is being spawn, there is no previous position of it.
or alternatively turn trigger into kinematic and write your own trigger
So will try to formulate my question one more time in case it was too abstract.
I want to find a point (green) on the surface (blue) of the area (yellow) of the two overlapping trigger colliders (grey), that is nearest to the another given point (red).
Preferably without iterating through points in the collider. There are can be some movement, but it's not always the case (so I can't rely on previous position and need to work with static colliders). The shape of the colliders can be more complex than boxes and circles. All this in 2d.
If you have the given red point you can use https://docs.unity3d.com/ScriptReference/Collider2D.ClosestPoint.html
If I understand correctly, this will give the point on the surface of the collider, not on the surface of the overlapping area.
It will give me the blue pint, right? But I need the green one.
See what happens if you use Vector2.zero as the cast direction
hello! is it possible to make a shader that does the effect shown in my scuffed image? Basically, you add the material to the mesh and it generates a water effect above it: waves on a set height and underwater effect in between the ocean floor and water waves level (less light, everything is blue etc).
I'm having an issue where my game character just floats randomly
You definitely need to provide some more context instead of slapping the code in here and expecting an answer
A video, specific instructions on how the code works, or stuff like that
Try loggin the values you use and see what goes wrong
I tried that
it stays the same
I'll record a video
hold on
What debugging steps have you taken so far?
What does "just floats randomly" actually mean?
Also looks like networking is involved which complicates things a lot
at first when I create a world everything is fine and I can jump and stuff
I fall down onto the ground slowly
what's confusing is
everything is only fine
when the caves are still generating
when they stop
I start to float
What debugging steps have you taken
but ik it has nothing to do with caves
well I've pretty much just searched through the code and tried to change some inspector values
nothing happened
I have this block of code that reads asset from a folder. It works fine in Unity Editor, but in standalone build, it cannot find the folder. How can I fix this ?
You should start adding log statements and questioning your assumptions about the code
The assets folder and .asset files don't exist anymore in a build
So how should I handle this approach ?
Thank you very much!
I have a couple of problems currently.
-
I have a shader that (should) apply bloom and can apply a dissolve effect. The bloom isn't showing, I have a PP volume with bloom active so I don't know why it isn't working.
-
I don't know how to go about making that dissolve effect happen while keeping the rest of the game paused. I've looked a bit into changing the time scale to 0 and coroutine looping a lerp for it but I can't quite get the logic working out so it doesn't stop entirely or runs the entire lerp during a single frame.
Help please β€οΈ
Yeah, I found WaitForSecondsRealtime but couldn't mentally figure out how to use it for what I want π
Being sick doesn't help my brain function though, and thanks for the shaders channel reminder!!
#archived-shaders that is if you are using custom shader for post processing, otherwise it's #π₯βpost-processing
Coroutine time await function will use scaled deltaTime. For things like animating UI you want to use realtime one so they won't be affected
I'll fiddle with it and come back if I'm somehow working myself into a mental dead end. Helps to have some code to reference too π
How do you usually avoid that something spawns inside another Object?
Or for example that something is perfectly placed?
E.g. Imagine you highlight some part of a Gameobject or whatever. You want to spawn in an Arrow pointing on that highlighted part.
So how do you programatically place that arrow that it does not spawn in the gameobject itself? This is more theoretically...
In the attached image it should spawn perfectly in the space outside the gameobject itself.
Are there some algorithms for this? How would you do that?
It draws the point outside overlap and not on the surface π¦
I'm trying Collider.Cast(Vector2.zero, results); and then using the first point in the results array.
Honestly I don't completely understand what is "cast shape into the Scene".
Am I using this function correctly?
No, because Vector2.zero is not a valid direction.
A cast moves an object through the scene, not moving it at all is not a cast, it would be an overlap
I see that was recommended to you... in that case the docs say what it returns
Additionally, this will also detect other Collider(s) at the collider start position if they are overlapping. In this case the cast shape will be starting inside the Collider and may not intersect the Collider surface. This means that the collision normal cannot be calculated in which case the collision normal returned is set to the inverse of the direction vector being tested.
Vector2.zero is (0,0), points nowhere and provides no direction - makes sense you would get nothing from trying it. I'd expect some warning or debug log though
Anyone?
I understand that, just tried what was said. I don't think it doing what I need anyway.
If I'm trying the yellow point as a direction the result looks like this.
So there no mechanism to get the overlapping area and working with it (find a point inside it, for example)?
I'm having trouble understanding what you want.
do you want to get a position that's in the overlap between the rectangle and the line?
I want to find a point (green) on the surface (blue) of the area (yellow) of the two overlapping trigger colliders (grey), that is nearest to the another given point (red).
Preferably without iterating through points in the collider. The shape of the colliders can be more complex than boxes and circles. All this in 2d.
hmmmm, that could get tricky fast
i'm reminded of stuff like https://en.wikipedia.org/wiki/GilbertβJohnsonβKeerthi_distance_algorithm
..which is basically collision detection itself!
I wonder if you could use non-triggers. You get a set of contact points.
not sure how usable that data would be
I am using 2022 unity, is there a place where I know which version of dotnet unity supports?
tbh, the most obvious solution to me is to do a batch of raycasts
I wanted, but the problem is that collision pushes objects away and I don't want to move them.
I am not sure about how you define the green dot?
is it like the closest point in the overlapped area to the red point?
yeah
so:
- intersect two colliders
- find the closest point
here's one thought
the green dot will be located at one of two places
Ideally to the surface of the overlapped area because red point can be inside of it, but yeah
it could be on one of the corners of the intersection area
or it could be the closest point to the original collider
but I don't see any obvious way to get those corners from triggers overlapping
I vaguely remember seeing a way to do this..
i feel like i'm back in my 4000-level algorithms class, haha
will this be on the exam
this is the type of thing that's extremely tricky to do in the analytically correct & general case - if you can make any assumptions or approximations anywhere it will help a lot
yeah
but if you want to do what you're describing, it's almost certainly going to mean iterating over collider points in some way - either to check, or to construct a new one from the intersection
I'd generate a density field(or whatever it's called) for each shape, intersect them and then do some vector math.π€
well yeah, this is a common case, it can be easy or tricky depending on the shape.
Not sure if the unity standard colliders provide help or more complexity here
but basically , an Idea is to find the edges of intersection
I guess (not a proof but my mind is kinda telling me this could be correct)
one of the two vertices that define the edge is the closest point.
(this will fail if the point is within the radius of the circle that bounds the overlapped edge)
so your time required is 2 * number of edges * time_required_to_constructed an overlapped edge to find the point.
What's the gameplay goal here?
is there a way to make a nuget package that only has
.net 6 version
to work with unity?
I am seeing only 4.8 being supported
No
π there must be a workaround or something no?
I think can't rely on vertices not only if the point inside this radius, but if it's generally located between vertices on one axis
A weapon hitbox (can be static or moving) should be able to spawn entity (another hit box, for example) in the place of a hit.
Find the nearest vertice, and determine the nearest adjacent. Then use math to find the intersection point between two lines
Since we're talking about geometry math...
I have a capsule (in 3D) that is intersecting with an infinite plane. How can I calculate the area of the intersection, as an axis aligned quad? Here's what it would look like, taken from the side and from the top. The red rectangle is what I want to calculate. The orange egg looking thing is the actual intersection shape, that I don't care about. I just need the bounding box around it.
I would also be satisfied with just the 2D version as a starting point. That would be the red line in the first picture.
annoyingly, you can't get collision events between two kinematic rigidbody colliders
what could possibly be causing this jerking movement on the camera? if it's static or attached to the player directly everything works just fine
public class CameraController : MonoBehaviour
{
public Camera mainCamera;
public float lerpSpeed;
private Vector3 position = new Vector3();
void Update()
{
position.x = Mathf.Lerp(mainCamera.transform.position.x, transform.position.x, lerpSpeed);
position.y = Mathf.Lerp(mainCamera.transform.position.y, transform.position.y, lerpSpeed);
position.z = mainCamera.transform.position.z;
mainCamera.transform.position = position;
}
}
fixedupdate vs update, I'm guessing
I am very interested in this red line case too π
is the player a rigidbody? if so, try putting Interpolate on
Interpolate does wind up making the object appear one frame behind where it should be, iirc
should've probably looked into the docs more
yeah I know what it does
oh yeah, this actually explicitly talks about camera problems :p
also, cinemachine tends to Do The Right Thing
it just forcefully recalculated the graphic on every fixedupdate iirc
well, the graphic's position
good catch, I missed the simplest case,
but yeah then I think the only way if you want to measure the distances is to loop all edges
and find the standard
closest point on a line segment
if you have too many edges, group then into rects or circles and only choose the closest group (more like space partitioning)
The problem is, I need the point to be on the overlapped area perimeter. If I'll check every vertice, I'll get the blue point, not the green.
And even if only "affected" by collision lines would be checked, the nearest point on this line can be outside overlapping area : (
Oh, your proposal about grouping can solve this
I am not sure what you mean by perimeter?
how is the perimeter defined here? +
in linear algebra, you just clamp t of your direction vector to something between 0,1
so you get a point on the line segment
I mean surface of the overlapped area (blue here), don't know how to call it right π
i have this txt file i want to use for my game. I want to import it into an array to be able to read every line individually. how would i do this. I had something working but found out this wasn't going to work on phones. right now i have
var txtFile = Resources.Load<TextAsset>("textfile");
this does read the file, but is not making it an array. how would i turn this into an array
split the text on newline
this seems to be working. thanks
Hmmm... still struggling to get the game paused while I'm running a coroutine for some shader lerping.
Currently, I've got the coroutine which loops until the elapsed time is past my animation duration (the actual lerping only works because I'm yield returning some fraction of a real second at the end of every loop). I'm trying to "pause" the game by just making it run in a while loop for the same duration in real time (using unscaledDeltaTime).
I even tried setting a variable at the start of my coroutine and after the internal loop to try to handle "coroutine is currently running" but when I made a while loop based on that, it made an infinite loop. Frustrating.
Just found something that might help.
Storing the coroutine function as an IEnumerator and checking if .MoveNext() is true - if so it is running?
Nope, doesn't work so good for me :\
Why would I need to create an instance of a scriptable object, if scriptable objects aren't living things in the hierarchy?
Is that like instantiating a prefab?
You can still create a new instance in the memory
It just depends on how you use your SO
Might not need it
I think more simple problem would be to find vertices of the overlap of two rectangles.
So only rectangles and just to find resulting shape.
Seems like this kind of problems more suitable for math.exchange, not for unity code-general. π
Ok thanks. I was watching a Unity video about them and saw the function and wondered why it would be used, I'll leave it for now. Thanks
maybe, but in reality if this is a game mechanic you're trying to implement you can get something approximately good enough with a lot less effort - there were a few suggestions already that would do it
if you can say that the overlapping colliders will always be two rectangles it's immediately easier to solve
Hey, can i get somehow list of collisions with points and normals from rigidbody? I tried using OnCollision events but I'm getting only last ContactPoint that it made.
I don't think I'm going to do anything super fancy with them. I've been exploring how to use them passing data across between scenes using delegates too.
I'm struggling a bit now because I dont want to use a singleton as I've heard they're not best practice but I can't seem to get my static class to subscribe to the delegates since they have no Awake or OnEnable function
How do you get static classes subscribed to delegates and events?
singletons are fine
not likely to dig yourself a hole with them, unless you're using them across, say different characters. But for creating single type systems of management, such as object pools, they are fine.
i don't like the phrase "not best practice"
it implies there is a Right Thing to do, and that everything else is a Wrong Thing
I need it to manage character data between scenes, and that data may change so will have a few functions on it too.
I've seen lots of videos where people talk them down so I assumed it was a beginner-friendly way of coding and there was better ways
As you can probably tell I'm very new to it all
Oh, I missed suggestions for alternative implementations? Or you mean not in this chat?
Singletons can be a headache if you realize they're not so single after all
for example: in one game of mine (a ripoff of Alien: Isolation, more or less), I started with the assumption that there would be one enemy
and one player, too
so I had lots of code that just reference the single static monster and the single static player
then I realized that I want to have multiple players (mostly controlled by AI; it's not actually a multiplayer game)
so I had to rewrite a fair bit
now I'm thinking I want to have multiple enemies, too, and that's gonna be...a fair bit of rewriting
Although, that's not exactly the problem I was originally envisioning: that's a change from "one" to "many"
that's always going to be a some work
The big problem I can foresee with singletons is realizing that some actors need to refer to one thing, whilst others need to refer to another
you need to go from "they just read the singleton" to "someone hands them a reference"
[12:08 PM]chemicalcrux: tbh, the most obvious solution to me is to do a batch of raycasts
Well... It implies there's a best thing to do and everything else is just not as good in some aspect, not that everything else is wrong entirely.
they're bad practice (tm)
I'd also have a read of this: https://xyproblem.info/
and think about whether this overlapping trigger thing you're trying to do is actually relevant to the problem you're trying to solve at all
Asking about your attempted solution rather than your actual problem
Thanks @heady iris . Makes sense, for things that could grow I should look at alternative systems. But for something simple like a game-manager like I'm trying to create, its fine?
Again, not necessarily a wrong thing entirely though. But think what ya want. Time for work.
Something with the "game manager" role makes sense as a singleton
there is a single manager for the game
i am being sardonic here -- I agree that such things are not the "Wrong Thing"
some people get very dogmatic about this stuff
probably after overdosing on Clean Code
Well, the problem is "weapon hitboxes should spawn another entities in the position of the hit". If there a better approach I would be thankful for the advice.
Raycast thing can work, but seems a bit inefficient and it seems that there should be a better solution considering there are only rectanges
Thanks for the input guys. I'm gonna crack on and use a singleton, but I've learnt a bit more about static classes and scriptable objects in the process so thats a plus too.
Very, very true. Lol
This is also why I love programming. There's ALWAYS more than one way to do something.
does it make sense that you need the point closest on the overlap, or should it just be whatever the centre of the weapon hits?
just to be sure are you looking for polygon-clipping?
have a look at the examples here:
https://www.tutorialandexample.com/polygon-clipping
Polygon Clipping in Computer Graphics with tutorial and examples on HTML, CSS, JavaScript, XHTML, Java, .Net, PHP, C, C++, Python, JSP, Spring, Bootstrap, jQuery, Interview Questions etc.
if this is what you are looking for, then I am not sure if you unity does provide such support for those things, but in general you can google convex (hopefully your shapes are not concave) polygon clipping algorithm, they are a bit tough if you have not implemented one before.
Sad to say I don't think there is a simple way to do it, unless unity has an out of the box support using its built-in colliders (I think it is doable because the colliders are fixed in shape).
Weapons can be long,
With raycast there are still the problem that I need to know that point on cast overlap is in jitbox overlap.
Yeah, seems like I need to implement some of these algorithms.
before you do so
there is a possibility, this might help !
have a look at these,
Clipper is kinda famous ig.
Thanks! I'll check it
Hey, i created game, there is login where you put key and login to get access but question is can anyone read memory and hack it that we will pass that screen and play ?
And how i can project game
you use external server validations and use something like a bearer token
I mean this screen sends req to my server and checks
But idk if they can just disable that screen and go on
100% agree with this. Its a sign of closed-mindedness (is that a word?)
idk that depends on your implementation upon received data
you need to make a validation
It's really wishy-washy
that's the part I don't like
it's vague Badness
hey guys, how to reset all rigidbody factors in script?
I reset player's position and rotation when the game is over (when enemy hits player). Then I change timeScale for a while and player is still moving, because of the previous Ridigbody.AddForce
You can also set the velocity to zero.
just velocity?
oh, sure, it works now, thank you
Might wanna reset angularVelocity too
If i have multiple triggers on a gameobject and one of the attached script calls OnTriggerStay() wich of the colliders does it pick to check for collision?
It's the other way around: one of the colliders caused OnTriggerStay to be called
I don't believe you can check which one it was.
If they're on the same GameObject or a child.. all of them
If you have two different kinds of colliders, you should put them on two separate objects, and have scripts on each one to handle those colliders
Is possible to create a scriptable object with another script in it?
For example i am creating a scriptable object called item with itemType, itemImage, etc
And i want that object to have another script in it, for exemple itemStats, with another set of variables
Then i have a problem where only one of em calls the method!
I think you have to do Public <Class> Name;
is it possible to create a script that automatically resizes imported imaages of a specific extension, they are auto resized? Would this work?
`using UnityEngine;
using UnityEditor;
public class ImageResizer : AssetPostprocessor {
void OnPostprocessTexture(Texture2D texture) {
// Check if the imported asset is a texture
if (assetPath.EndsWith(".png") || assetPath.EndsWith(".jpg") || assetPath.EndsWith(".jpeg")) {
// Resize the texture to 1024x1024 pixels
TextureScale.Bilinear(texture, 1024, 1024);
// Save the resized texture to a new file
byte[] bytes = texture.EncodeToPNG();
File.WriteAllBytes(assetPath, bytes);
AssetDatabase.ImportAsset(assetPath);
}
}
}`
I'm not super savvy with coding
do you want to change the maximum size of the image asset?
Yeah, I'd like to set that so they all import at 1024 by default, and I can adjust some accordingly.
physics events will also only be picked up by 1 component on a gameobject/ children
Does a the OnTriggerStay method count as physics?
of course
hm
And that object will get the script inside of it?
how do i decide wich of the colliders gets used for that?
i think you drag and drop it onto the scriptable object or select it inside the Editor
You can't via code afaik. You have to setup your hierarchy how you want.
OR
You make your own physics events, so you only have 1 component listening to the physics events.. and then everything else listens to your custom physics events
note that I would not say it "gets the script"
if you have a serializable type called Foo, you can make a field of type Foo
public class Bar : ScriptableObject {
public Foo foo;
}
you can assign an instance of Foo to that field
if Foo is also a ScriptableObject, then you can create an asset that holds a Foo and assign it to the field on a Bar
eh?... i have no idea how to do that...
What if i place the other collider in the parent? would the collider call the OnTriggerStay method from the parent aswell?
the collider sends the message to components on its own game object
also, if you have a Rigidbody on a parent object, it will receive collision events for its child colliders
isn`t a rigidbody necesary if i want trigger collision checks?
only on one of the colliding objects
so i don't have to put it on the trigger object?
If the object(s) you expect to hit the trigger has a rigidbody.. then no, the trigger doesn't need it
but the object that is the trigger is actively moving...
There could be a case where the objects hitting the trigger don't have rigidbodies, so you would put the rigidbody on the trigger
sigh
Only ONE of the colliding objects REQUIRES a rigidbody for the collisions to work, more than one rigidbody is fine, in the cases that they're required
is the any way to do lambda "equals" in C#?
like that:
int num = (condition) ? 1 : 2; // that's default one
int num =
{
if (condition) return 1;
return 2;
};
not sure I understand the question
Do you mean a switch expression?
Hya. I'm trying to drag and drop drawn rects in the inspector (custom editor script). I have a (background) rect (rect0) made with GUILayoutUtility, and used with GUI.BeginClip, within which all the dragging action should take place. Then I draw a tiny rect with EditorGUI.Drawrect (rect1). I am able to detect clicks in rect0 ( with if rect0.Contains(currentmousePosition), but I cant use the same on my tiny, draggable rect1. if (rect1.Contains(current.mousePosition) never fires.. Anyone any idea?
public override void OnInspectorGUI()
{
DrawDefaultInspector();
Rect rect = GUILayoutUtility.GetRect(0, 1000, 200, 200);
GUI.BeginClip(rect);
Rect rectP1 = new Rect(bez.p1.x, bez.p1.y, 10, 10);
EditorGUI.DrawRect(rectP1, Color.red);
GUI.EndClip();
Event current = Event.current;
bool wasMouseDown = false;
if (rect.Contains(current.mousePosition))
{
if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
{
Debug.Log("Left-Mouse Down");
if (rectP1GUI.Contains(current.mousePosition))
{
Debug.Log("clicked in rectangle 1");
}
}
}
like that one:
int[] nums = new[] { 1, 2, 3, 4, 5 };
nums.Select(n => n % 2 == 0 ? n : n + 1); non-lambda
// lambda
nums.Select(n =>
{
// do smth
if (n % 2 == 0) return n;
return n + 1;
});
nums.Select(n => n % 2 == 0 ? n : n + 1); non-lambda
This is a lambda
why are you saying it's non-lambda
not mean not "big lambda"
This is a ternary operation. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator
I don't understand the question.
Are you asking how to write a lambda with multiple lines?
instead of a lmabda expression?
I am asking if there is a way to "equal" a variable to the lambda
Yes that's called a delegate
Func<bool> myDel = () => true;```
we can do this:
bla = (bla % 2 == 0) ? bla : bla + 1;
but cannot do this:
bla =
{
if (bla % 2 == 0) return bla;
return bla + 1;
};
Func<int> myLambda = n => n % 2 == 0 ? n : n + 1;
var result = nums.Select(myLambda);```
without additional function?π€
there is no additional function
Func<int> is just a delegate type
Func<int, int> myLambda = n => {
return n % 2 == 0 ? n : n + 1;
};```
Here it is again without compile errors
Func<int, int> means "a function that accepts an int parameter and returns an int"
ok, thank you, I guess it's impossible to do what I wanted in C#
No I think it's totally possible
I still have no idea what you're asking about
you can literally just Do It
I do like it
Maybe you don't like the word "Func"
We can do it without the word Func
public delegate int MyCustomDelegate(int param);
void Example() {
MyCustomDelegate ex = n => {
return n % 2 == 0 ? n : n + 1;
};
var results = myArray.Select(ex);
}```
this appears to be entirely a matter of syntax
you can't write it that way, because that's not how the C# syntax works
but you can write it this way
I have understood that now
ok, thx
the next question then: Is it nice to do smth like that in Unity?
private readonly (((float min, float max) neg, (float min, float max) pos) x, float y, ((float min, float max) neg, (float min, float max) pos) z) spawnPos = (((-13, -6), (6, 13)), .09263992f, ((-11, -6), (6, 11)));
i'm scared
Unity
if you are feeling Masochistic, you can certainly use tuples
but I recommend just making an actual struct
yeah
no this is not valid syntax
I know, but it is spawn for Unity
yes
everything would be a Unity question by that criteria
how do I install Windows (so that i can run unity)
nop, that one was certainly unity question
No, this is what we call Primitive Obsession.
it hurts
doesn't this tuple looks quite nice?
it looks like a struct that got run over by a train
No. This is unreadable and unmaintainable.
should I really do it in struct then?
just make structured/named structs and do it that way so you don't want to kill yourself to read the code
Yes
it's all basically the same thing to the computer
that's the answer!
Programmer are not computer unfortunately.
so , I decided to take a leap of faith and try my luck at compiling a .net6 library to 4.8 framework, to use it inside unity.
Any general tips so I can ensure my compatibility with unity?
or is it generally speaking, if it runs under 4.8 framework, it will run in unity?
Hi every one so I made a quick and easy code for my first person camera movement. Sadly when look to much to the left I can see my player and my camera seems higher then I placed 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.
please do not send photos of your screen
Oh sry
you can use win+shift+s to clip part of your screen on windows
assuming you're logged into discord on this machine
use code blocks or one of these paste sites for code
Any ideas why in visual studio class Ping is accessed normally and everything is good, but then when I try to build the game it shows that class Ping cant be accessed or found
what is Ping from? what kind of build are you making?
Why I can't store AttractorData[] AttractorStructs; I try NativeArray but there's error : BallData used in NativeArray<BallData> must be unmanaged (contain no managed types) and cannot itself be a native container type.
public struct BallData
{
public int Identifier;
public Vector2 Position;
public Vector2 Force;
[NativeDisableContainerSafetyRestriction] public AttractorData[] AttractorStructs;
}
public struct AttractorData
{
public float Force;
public Vector2 Position;
public Vector2 Direction;
public int AttractionType;
}
Hello Iβm trying to make a mechanic in the game where I can command troops from 1-20 with formations but I donβt know where to start
hey, i have a problem to get the audio sources on a gameObject (it is a prefab maybe it is the problem)
AudioSource[] audioSources = GetComponents<AudioSource>();
I assume that script's on the same game object as the AudioSources?
Did you try replacing AudioSource[] with var? π
what is the problem? Show the inspector of the gameObject
there is an inspector for each game object ???
of course there is Unity 101 basics, you should know this
a...
In the default UI layout, when you have a game object selected, it's on the right hand side of the screen
somewhere here?
That entire window is the inspector π
no, the whole inspector for the complete game0bject
how can you not know this, you added AudioSources to an object did you not
the script add audio Source
well if the script added them why do you need GetComponents?
You cannot use managed arrays in jobs, you have to use NativeArray. But also, you can't have nested NativeArrays, which it looks like you're trying to do.
Yes. In each ballData contains Attractor info and count of it can be greater than 1. And I want to know how I can store it
i use GetComponents to add them into a list which each frame low the volume of each element to smoothly stop the sounds between scenes
@knotty sun
Hay im making a turn based game and the enemy turns are not very computationally heavy so they end up happening almost instantly and all the enemies move at basically the same time, how would I go about slowing this down so it looks a little nicer and stuff?
You could store all the attractors in one combined array and store a index range in BallData so you know where to read from the combined array. You could also use NativeMultiHashMap to create a hashmap of BallData to multiple attractors.
you are missing my point. If you add the AudioSource components in script you alreasy have a reference to add to your list, you dont need to use GetComponents
ok i will try
thanks
I love first option π
but i still don t understand why it don t work
in my script I basically go through enemy.TurnLogic(); for each enemy during thier turn is there a way i could wait until say the movement animation of one enemy is done before the next one's turn
you still have not explained what you mean by 'don't work'
there is 1 audioSource on the gameObject, and when i use GetComponents i get 0 audioSources
ok. So show the inspector of this gameobject in play mode once the audiosource has been added
Does anybody know how to get a bullet list in textmeshpro?
what?
I would think to create a queue of movement coroutines, then maybe use a second coroutine which would pop a movement off the stack, execute it and wait for it to finish, and repeat until the queue is empty. That way you could calculate all of your movements ahead of time and easily determine when all are complete.
Plz could anyone tell me if there is an error unity keep saying that "skull" could not be found
public class Area : MonoBehaviour
{
public skull[] enemyArray;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
foreach (skull enemy in enemyArray)
{
enemy.chase = true;
}
}
}
something like this
you mean the array of TextMeshPro?
[SerializeField] private TextMeshPro[] texts;
do you have a script and class called skull?
Bullet list is those dots on the left
no
well what do you expect then? Magic?
i basically want a dot (bullet) before every new line
you already asked this in #π»βcode-beginner , and you were asked to use correct code tags.
