#archived-code-general
1 messages ยท Page 330 of 1
Fair
The Zen of Python
tbh the whole argument is moot. In a team you use the convention of the team. For yourself you do what you want because nobody else gives a shit
To be a pedant, following the convention of the community makes collaboration easier and more seamless.
not the way teams work. the project leader is the boss as far as this is concerned because, at the end of the day, it's his ass when the shit hits the fan
Unless you are working on C++ which doesn't have "official" convention
If it's a personal project or you're the team lead, then you're boss
Which I think is a very common scenario for a lot of us here
yep and no one gives a rats arse what you do
If I coded like an ape, I think people would help me less
what makes you think you don't?
I follow convention, use a linter, and I have seen my code from 6 months ago
if your project survives long enough, your old work starts feeling like someone else's work (:
so I try to be nice to my future self
so far I have been moderately successful
but that is still 'just' your opinion
It is my opinion that using Assembly is a bad choice to program a game
It is subject to disagreement, however.
But it is plain and obvious to most
The existence of a continuum between bad code and good code doesn't mean good code doesn't exist
really? You would never have survived the '70's
Assembly has not survived for game development beyond novelty projects, and for that I am grateful
I once met another code wizard that coded network protocols in Assembly before the invention of TCP/IP
Mind-boggling
well, we still write device drivers in ASM and without them you wouldn't have nice new bright shiny toys to play with
Embedded engineers are to me what software engineers are to average people. Touching assembly is ugly. How they manage to stay organized is beyond me
like anything else, practice, practice, practice and a damn good memory
What about massive systems where the scope of the project far exceeds memory? There are no convenient organizational features I'm aware of. It seems like no-man's-land for code
there are ways, but not convenient, one project I worked on which had thousands of scripts files used a numbering sequence for organisation. not nice but it works
Hello, sorry for interupting here but is there anyone who could help me with my scene colors?
I see only yellow color in scene
does not sound like a code problem
Thanks
if I have this code to move a platform it should be consistent right? Because its on the fixedupdate but idk why its not. I have a platform at 5 speed with 2 points and never bugs out and then i have another with 4 points making a square at 3.5 speed which is less and it just goes to the infinity and doesnt follow the path:
void FixedUpdate()
{
rb.velocity = moveDirection * speed;
if (Vector2.Distance(transform.position, points[nextPlatform].position) < 0.1f)
{
nextPlatform++;
if (nextPlatform >= points.Length)
{
nextPlatform = 0;
}
directionCalculate();
}
}
private void directionCalculate()
{
moveDirection = (points[nextPlatform].position - transform.position).normalized;
}
does gravity calculation differ based on whether im using root motion or not?
You calculate the direction to move in FixedUpdate
The rigidbody then moves in the physics update (which happens after FixedUpdate)
Suppose it's going right, and then starts moving up
If it overshoots the point, it'll be too far to the right
it might even be moving slightly to the right, too, since you calculated the move direction before it made its last move to the right
when it was still a bit to the left of its destination
so what i should do? I noticed if the platform is going only in 1 direction like up and down or right and left it doesnt happen
it just happens on the ones that goes in a rectangular way
this is what's happening
i'd suggest doing two things
calculate the move direction every FixedUpdate, so that it will correctly move towards the destination
i'd also clamp the velocity based on how far away the destination is
so that you don't overshoot it
you could also just use Vector2.MoveTowards to calculate a new position and then pass that to rb.MovePosition
that way, you never overshoot a point
yeah taking the direction calculate at the end of the fixedupdate seems to have fixed the problem
Btw when i was with the update it occurs sometimes but in fixedupdate the bug is consistent, this means if now is working properly on fixed it will always do?
It's still possible to overshoot the goal if you only fixed this part
it's just less likely, since you are always moving straight towards the target
how could it still happen if the direction is being calculated all the time?
overshoot the goal means it could happen right?
Is there any way to move a YieldInstructor as IEnumerator?
It's confusing that it's not even derived from it
notice that you use IEnumerator when writing a coroutine
not, say, IEnumerator<YieldInstruction>
you can yield literally whatever you want
Unity checks if the value you provided is an IEnumerator, a YieldInstruction, etc.
I don't want to yiled it, I want to MoveNext it manually instead
I can't seem to be able to get the seconds from WaitForSeconds to await it
you can't, because a YieldInstruction is not an enumerator
I'm pretty sure that WaitForSeconds is handled entirely on the native code side
[StructLayout(LayoutKind.Sequential)]
[RequiredByNativeCode]
public sealed class WaitForSeconds : YieldInstruction
{
internal float m_Seconds;
//
// Summary:
// Suspends the coroutine execution for the given amount of seconds using scaled
// time.
//
// Parameters:
// seconds:
// Delay execution by the amount of time in seconds.
public WaitForSeconds(float seconds)
{
m_Seconds = seconds;
}
}
given that this is the entire class
Yeah, and the seconds are internal
You can pull them out through reflection, of course
Oh, sounds interesting
Yes, quite what I'm trying to do
You'll have to do what Unity winds up doing: check if the value is a WaitForSeconds, an IEnumerator, a CustomYieldInstruction, etc.
I think they have something like
if (e.Current is WaitForSeconds w)
it's icky, but that's what happens when you're getting handed an object :p
I'm trying to make a StartCoroutine method, which, #if UNITY_EDTOR, runs my method with asyncs, otherwise calls MonoBehaviour.StartCoroutine
Just use async tho
It works same as coroutine if not better
Still runs on main thread (because Unity magic)
Do you mean not implementing a custom StartCoroutine method or simply using async instead of the Coroutines?
Yes
not implementing a custom StartCoroutine method and simply using async instead of the Coroutines
Why they are separate options
And so I can get that m_seconds using reflection if it's WaitFroSeconds?
Yeah.
I'm sorry, I meant "not calling the MonoBehaviour.StartCoroutine method in my own StartCoroutine"
And, I mean, I don't think async should be used if we already have coroutines on run time
Why? Async is more brand-new and Coroutine is just there because async wasn't exist when Coroutine was introduced.
I don't think awaiting a task delay is more accurate though?
And Unity doesn't support .NET 6 for periodic timer
Accurate in what sense? You can just check with timer or use Awaitable.WaitForSecondsAsync if you're on supported version.
Or use UniTask they should have equivalent
Only inaccuracy is that game time might differ from what Task.Delay checks
Not the problem with async-await
I have a problem. When i dash with my player, if after the dash im inside the panda collider he will just push me down the ground, is there any way to fix this?
Have you asked the panda to lose some weight? There isnt really enough info to go off here besides saying your dash shouldnt put you inside another collider to begin with
my dash makes me avoid all collisions with enemies until it finishes
A lot of this depends how you're actually moving. You could compute depentration if via physics and try to move the player outside the area
thats my playerMovement
ofc it only happens if the hitbox is big, if its from an enemy from my size it will just hit me into one side
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what i send before was a paste bin, now this is a hastebin
but idk the diff
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
what you sent before was copy/paste. Not paste the link
Which was so long so discord converted it in file
oh my bad then, i just hit copy on pastebin and that was the result
I must have do something wrong
How can i add a "trail" that shows where the player is going too land?
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 0;
Vector2 direction = (mousePosition - transform.position).normalized;
float appliedForce = Mathf.Lerp(minJumpForce, maxJumpForce, Mathf.Clamp01(holdTime / maxHoldTime));
rb.AddForce(direction * appliedForce, ForceMode2D.Impulse);
}```
like in angrybirds
trajectory ?
You wanna predict where the character will land?
I think that is usually done with many raycasts as physics involved ๐
Yes
if (normalizedDistance >= 0.5f) // start at half the distance
{
//float dot = Vector3.Dot(toCenter, spawnPoint);
Quaternion spawnFacing = Quaternion.LookRotation(spawnPoint, Vector3.up);
Quaternion rotationToCenter = Quaternion.LookRotation(toCenter, Vector3.up);
float angle = Quaternion.Angle(spawnFacing, rotationToCenter);
Quaternion rotation = Quaternion.RotateTowards(spawnFacing, rotationToCenter, angle * normalizedDistance);
spawnPoint = rotation * spawnPoint;
}
spawnPoint is a point in the unit circle that is converted to a vector3 the following way: spawnPoint = new Vector3(spawnPoint.x, 0, spawnPoint.y).normalized.
normalizedDistance is the player's distance from (0,0,0) divided by some number set in the inspector (in this case, 3).
toCenter is the direction to (0,0,0).
Should this not rotate the spawnPoint (which is a direction at this stage of the spawning mechanism) towards facing (0,0,0) based onnormalizedDistance? How do i do that?
You can calculate base on initial force and gravity and all, but it does not put the obstacles in count, so that part you'd do shape cast or something.
thank you so much : )
To be clear, even when the result of angle * normalizedDistance is in the thousands, I am still getting points that are facing away from (0,0,0)
I guess you want your object to look at origin point the more they are far from it?
I want my spawn point to be more towards the origin point the further they are away from it
Hm, bit confusing, try log some values and see if they are correct for your intention?
im not sure what to log here besides the final value and the angle (which is how I know the angle is in the thousands). They're all quaternions and those won't mean anything to me.
Actually
You are rotating spawnPoint again with LookRotation to the spawnPoint
I guess what you want is simply rotation * Vector3.forward or something
I tried doing Quaternion.Inverse(spawnFacing) * rotation * spawnPoint
actually wait I think I need to swap those two first ones
or possible Vector3.forward like you said
let me try
Multiplication order is ever confusing
well left hand side is the start rotation right hand side is the rotation you're "adding" to it
well that you just make sure the quaternion is on the left
Anyways your rotation already has the rotation for the spawnPoint included
So technically you'd just want unit vector to rotate alongside with it
multiplying the rotation with Vector3.forward gives the same result as rotation * Quaternion.Inverse(spawnFacing) * spawnPoint and it's really weird
That's normal
it looks like it's working but in the wrong way lmao
Because Quaternion.Inverse(spawnFacing) * spawnPoint should be just forward vector
maybe? Idk. It should be the rotational difference between the look rotation and the current rotation I think, which is not always a forward vector maybe?
No spawnFacing you made was LookRotation to the spawnPoint
So "undoing" it should be just forward vector
ah
hold on I need to make a quick gizmo component to show you the result
its strange
my player is selected
here the angle is in the thousands since the normalized value is over 2
I'm doing this: for the last line in that if statement spawnPoint = (rotation * Vector3.forward).normalized;
And what shows the spawnPoint here?
What could be affecting it like this is that this code is in a loop, where if the position is invalid it increases the radius a bit and tries again. So that's why they're in lines like that. But why are they in lines like that? Each time it loops it does another random point.
without looping it looks like this:
they seem to always spawn to the right of the player, on the positive x axis
I see what I'm doing
hold on
I'm spawning the points around the player
i need to remove the player's rotation as well
yes, since this is all in world coordinates around (0,0,0), I treat that in local space and use transform.TransformPoint
yes works good now! Thanks for your help cathei!
hey guys, lets say I have a direction A and a cube
and I want to get the X degrees
how can I calculate it
the dotted line is the normal
in 3D space or 2D space?
3D space
to put it in even better perspective, let B be a point in space. I want to know how much to rotate the cube so that B will be the reflection of vector A on the surface on the cube
so given A and B coordinates, I want to rotate the cube much enough for B to be reflection of A
that's actually what I need
Why doesnt my script call the second script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlashLightOnTable : MonoBehaviour
{
Player player;
void Awake()
{
player = GameObject.Find("Human").GetComponent<Player>();
}
// Update is called once per frame
void Update()
{
}
public void OnMouseDown()
{
Destroy(gameObject);
player.PickUpFlashlight();
}
}
There are no errors in the console
Can you clarify more what reflection you're trying to achieve? Because there is a reflect method you can use to calculate where a vector should point after reflecting on a surface (you pass in the surfaces normal)
But if you're rotating the cube, this now changes
how have you confirmed it doesn't
Because in the second script when PickUpFlashlight is called the player is supposed to hold the flashlight but that doesnt work. So i set an Debug.Log("Activated") In the second script to check if it's even being called but nothing shows up in the console either
okay and have you confirmed that the code you've shown is actually running?
Ye, the gameObject gets destroyed when i click on it
then either you have an exception in the console that you are ignoring or PickUpFlashlight is being called.
oh the other possibility is that something else is destroying the object
No, im just an idiot. I just noticed i put the second script in wrong GameObject bruh
But thanks for the suggestions lol
second script in wrong GameObject
so then you did have an error in your console that you were ignoring
No, there were still no errors in the console. The second script was supposed to be put in the Player, but istead of putting it in the Player i put it in the SpotLight which is also in the player which is supposed to be the flashlight itself
But there were no errors in the console
unless your spotlight is also named Human then you absolutely had an error that you were ignoring
Huh hows that
you would have received a NullReferenceException when attempting to call the PickUpFlashlight method on the player variable
Oh i did get that yes, but since there are some other errors in the console not related to that script i thought it was just another error that wasnt related. My bad
sorry im a bit new to coding in unity
oh my god. if you literally have errors in the console then do not insist that you do not have errors in the console
Okay
Can anyone help about this problem or any idea ๐ซค
https://discussions.unity.com/t/graph-view-list-view-problems/363699
use a raycast and use the hit.normal
oh wait I missread your drawing
I think for your case Quaternion.FromToRotation should be the solution, use your first direction with the normal, and that will give you the rotation between your vectors
then apply that rotation to your normal and you should end with your wanted direction
also, since this is a cube btw you can just flip your y direction
[RequireComponent(typeof(Tilemap))]
public class AStarGridForTilemap : MonoBehaviour
{
[SerializeField]
private LayerMask obstacleMask = 0b1101101100011;
public void GenGrid()
{
if (AstarData.active.data.graphTypes == null)
AstarData.active.data.FindGraphTypes();
GridGraph graph = AstarData.active.data.AddGraph(typeof(GridGraph)) as GridGraph;
InitializeGraph(graph);
Tilemap map = GetComponent<Tilemap>();
graph.AlignToTileMap(map);
AstarPath.active.Scan(graph);
}
private void InitializeGraph(GridGraph graph)
{
graph.is2D = true;
graph.collision.use2D = true;
graph.collision.mask = obstacleMask;
graph.collision.diameter = 0.95f;
graph.rotation.x = 90;
}
}
[CustomEditor(typeof(AStarGridForTilemap))]
public class AstarGridForTilemapEditor : Editor
{
public override void OnInspectorGUI()
{
if (GUILayout.Button("Generate A* grid for tilemap"))
((AStarGridForTilemap)target).GenGrid();
base.OnInspectorGUI();
}
}
I have the above code set to generate a grid graph for A* pathfinding that's aligned to a tilemap. However, whenever the code is compiled (after an edit to some script), the created grid graphs are removed
And I'm not really sure how to prevent their removal
Hey everyone, I saw a book recommended for beginners to C# quite a few times online, but, it was published Jan.2022, is there anything that would be incredibly different in that amount of time or mostly similar?
there wouldn't be any significant changes, everything in there should still apply
The basics are same, only additional features
You should look what version of C# is tho
Unity is bit late for adapting modern C# anyways
It says C# 10 .Net 6 on the cover?
That's good enough, Unity uses, eh, C# 9.0
C#10 would still work with C#9 mostly, though?
Yeah most of it will work or easily converted
Thanks @calm talon @leaden solstice :) Appreciate it
any idea why my score suddenly isnt showing up in the simulator?
well, just found out some shader went missing when i havent touched anything but my code
edit: aaand it broke again for no reason
PLEASE does anyone know how drag works in unity and how it's calculated? It's been driving me CRAZY
There are many ways to implement it. You'll need to share some more context and info on what exactly you've tried so far.
Here's the entire situation. I am trying to restrict the horizontal movement ofmy character by setting the character's velocity to a max speed. However, at the end of fixedupdate, this value is reduced by drag. I then decided to reduce drag to zero, which fixed that problem, but introduced another, because now my character jumps much higher than intended. Now I would like to apply drag to my character but only vertically, because I want both my jump height to be normal and for drag not to apply horizontally
Which is why I've tried to find some sort of formula for applying vertical drag manually
Drag is basically reducing the velocity by some percentage(of flat amount?) every frame.
But I think it would be better to just adjust your jumping height/velocity, instead of introducing a drag for it.
well my problem is that I only bring drag to zero when I've reached max horizontal speed, so currently my character jumps much higher running than when its standing still
I could show a video of it if you would like
Sound like some very unreliable logic. Maybe avoid modifying the drag at runtime and find some better solution
should I be using drag to decelerate the player?
that is currently how I'm using it
Depends on what kind of controls you want. I'd say no.
I'm planning to have movement where the character doesn't stop and start moving immediately. I plan for the character to accelerate until reaching a max speed and decelerate until it stops moving
idk I kind of have a feeling like I shouldn't just be ditching drag, but it has been rather difficult to deal with
Should be pretty easy if you use your input to controll the acceleration instead of velocity
The jumping can then control the velocity separately.
what do you mean by that?
Exactly what I said. You should probably know from school that acceleration determines how velocity changes over time. And velocity determines how position is changing over time. By controlling acceleration you would be able to speed up and slow down over time.
I already do that from my script, I'm just having problems with setting a limit on the character's velocity
without drag affecting it
You can limit it with a clamp or something similar
also when does drag affect velocity? I have heard previously that drag apllies to the velocity only until after the body of fixedUpdate executes
thank you I think I will use this
I've hit a catch 22 where in I have a separate deceleration value if a player is above the intended speed (I want them to accumulate speed) and that works fine for maintaining speed. The issue however arises that using that separate decel value makes it nearly impossible to turn. Is there a work around? Since the whole "acceleration is change of speed over time".
Drag is applied in the physics update(which happens to be right after the fixed update) among other calculations.
You'll need to share more info about your issue and it's context.
Maybe record a video of what's happening first
The dash deceleration is better at maintaining speed but because I'm still checking for input as part of this argument that means I maintain very little control.
aight
Well, what kind of behavior do you want during a dash?
Trying to record a good angle.
Car like turning with highly reduced deceleration. Additive speed game.
Car like movement/steering is pretty complex actually. There are a lot of counteracting forces involved
then would it be a better idea to decelerate the player manually?
like, by using RB.addforce
If you're setting velocity, I'd keep all the logic limited to setting the velocity
You could lerp(move towards or some other way) the velocity to 0 when there's no input
I see, thank you
Any input on what I'm doing wrong here with the coyote timer? I feel like this makes sense but it isn't working out.
Should it be greater than?
Maybe you should explain what's happening and what isn't.
Well I fixed it. It was greater than.
And it's a coyote timer. Doesn't really warrant as much explanation.
We need to know what is actually happening....
We know what coyote timers are, that doesn't explain in what specific way yours wasn't working though
I get that, but I'm not sure how I'm supposed to explain that the thing that doesn't eat a double-jump when leaving a ledge within a certain amount of time isn't working when I leave a ledge. It's commented and in the end was a minor syntax error.
"if in air but you didn't jump set the jump count to one higher unless you hit the timer"
Well, you say the words you just wrote....
But at the same time you post the code
Because that is far from the only issue people have with coyote jump. For example, for some people they are able to do it after any amount of time
Sometimes I just need an extra set of eyes. I'm sorry I really don't mean to come off wrong. I'll work on specifying issues going forward.
Hello, is there any way to assign StartSomethingInternal to a value of type Coroutine and return it without using Unity's StartCoroutine etc.?
public void StartSomething(IEnumerator value) => StartSomethingInternal(value);
private async void StartSomethingInternal(IEnumerator value) =>
await StartSomethingAsync(value).ConfigureAwait(false);
private async Task StartSomethingAsync(IEnumerator value) { ... }
Based on the snippet you provided, I don't know why you would want to have it return a coroutine. Why not just start a Coroutine in StartSomething?
Also you may want to look into the Awaitable class if your version of unity supports it if you're doing async stuff.
*I also don't know of a way, or I would have just told you
That's because Unity doesn't provide Coroutines, which can run in the Editor. The context isn't really necessary, I just want to find a way to assign an async Task to a Coroutine
The reason why I don't simply use tasks is that I want to create an extension StartCoroutine method, which, in the Editor, runs according to my functionality, otherwise simply calls MonoBehaviour.StartCoroutine
well you should definitely look into the Awaitable class to see if your version of unity has it. Also, there's an editor coroutine package you can install! But, if you don't want to install any packages, I usually just make a new game object, attach some dummy monobehaviour to it, and use that as a "coroutine holder". I set the hide flags for the object so it doesn't appear in the hierarchy.
Editor coroutines don't work properly in the Editor, as WaitForSeconds cannot be calculated properly without Update, which in the Editor is called only when any changes are made
So Editor Coroutines package doesn't really fix anything
the editor coroutine package provides an "EditorWaitForSeconds" class which waits seconds in the editor using unscaled time
I have installed this package already, but now I forgot whether I have tried to use EditorWaitForSeconds...
[field: SerializeField]
what is the "field" thing in the code block above? why put it?
it applies all the attributes in the []s to the auto-implemented field of a property
without the field keyword there it would try to apply it to the Property
what is this "property"?
A property is a way to encapsulate your data. It's sort of like a method. They're usually used to expose fields that you want read outside of the class but not written to. This is an auto-implemented property:
public string Name { get; set; }
```You can also implement them yourself:
```cs
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
private string _name;
```Like I mentioned above, they're useful for data encapsulation. For example, maybe we don't want the name of this object to be changable by outside classes, only itself. We could do this:
```cs
public string Name
{
get
{
return _name;
}
}
private string _name;
```Which only has a `get` as you can see. OR we could do:
```cs
public string Name { get; private set; }
``` Which, as you can see, has an access modifier on the `set`.
ohhhhhhhhh i see now
thank you for the explanation
So I've tried out EditorCoroutines package, it then took a while to be able to use its namespace, and was confused why this does work properly, as you can see in the image above, when simply starting a Coroutine.
private IEnumerator MyCoroutine()
{
print("<color=blue>MyCoroutine start</color>");
for (int i = 0; i < 10; i++)
{
yield return new EditorWaitForSeconds(1f);
print($"MyCoroutine - i: {i};");
}
print("<color=blue>MyCoroutine end</color>");
}
I had a look on the EditorCoroutineUtility class and it seems like it does have its own method. Using it works properly in the Editor, which makes me a bit upset I have been trying to implement my own solution for a while.
EditorCoroutineUtility.StartCoroutine(MyCoroutine(), this);
Thank you for your help. You have saved my time I would've wasted ๐
I was willing to reply to this message.
hello could someone help me tell me what to do I'm trying to create a code in C# to make a character move from right to left and up and down I followed a tutorial but certain things I write don't work colors would someone need to install more so that they can understand my program (I'm on visual studio and I already have the C# dev kit)
start with the pathways from !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Okay thanks
it might be hard I'm French
Have more confidence. Being French shouldn't be hindering your learning ability.
Well, then you're going to learn Unity and English simultaneously
I agree with you but I don't have much time it will take me years
I would doubt that
If you're able to understand English you hear, you'll be able to use pathways
Also there're subtitles
Okay I'll try but my problem concerns visual studio, do they talk about it in there?
I have a problem. When i dash with my player, if after the dash im inside a big enemy collider collider he will just push me down the ground, is there any way to fix this? This is the code of the player movement:
https://hastebin.com/share/dosocacore.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
Im having a problem where i have a impct particle effect for where my gun shoots but when i move backwards the particle just attaches to my camera. can anyone help me out?
You'll need to provide more info if you need help.
what info would you need?
Everything. Your initial message doesn't explain anything.
If it's hard to explain in words, record a video.
alr give me a minute
- What exactly is the issue? What do you expect to happen, vs what's happening.
- Share the relevant code.
- Describe the steps you took to debug the issue and what you figured out from them.
Mp4 please.
alr
the code for the gun is
using UnityEditor.UIElements;
using UnityEngine;
//using static AutomaticGunScriptLPFP;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 30f;
public Camera Maincamera;
public ParticleSystem Muzzelflash;
public GameObject Flareeffect;
public GameObject FlareEffect;
public float Muzzelforce = 30f;
public AudioSource shootAudioSource;
public SoundClip soundClip;
public AnimationClip recoil;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
shoot();
}
void shoot()
{
shootAudioSource.Play();
Muzzelflash.Play();
if (Physics.Raycast(Maincamera.transform.position, Maincamera.transform.forward, out RaycastHit hit, range))
{
Target target = hit.transform.GetComponent<Target>();
target?.TakeDamage(damage);
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(hit.normal * Muzzelforce);
}
GameObject MuzzelGO = Instantiate(Flareeffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(MuzzelGO, 2f);
}
}
}
}
public class SoundClip
{
internal AudioClip shootSound;
i followed a tutorial since im fairly new to programnig and having touble finding whats wrong with it
done
So, what happens actually? To me it looks like you hit your own character.
yes thats the issue
i tried removnig the collision from mthe capsulle but it didnt change anyhting
You could use a layermask in your raycast to ignore the collider of the character.
give me a second to try that thank you
sorry but where would i do that? 
again im fairly new to coding haha
this is my first project
Check the documentation for raycasts. The method can take a layermask as a parameter. There should be examples too.
where is tht
Are editor console entries cached anywhere?
Due to automatic "Clear on Recompile" I accidentally lost a very important log, that could help me fix an error.
Google "unity API raycast"
ok thank you
Yes. In the !logs files.
!logs
Thought it's cleared every session, so keep that in mind.
thank you
So i have different tile images but i want to copy them or from the editor for other directions
how do i do that
but you get what i mean right
Hello there !
I'm working on little thing, the idea is just to get audio files from player's folder (documents/My Games/gamename/radio) to load them into the game.
I can't use coroutine so I used async operation to do that, in this code everything working well but I'm just asking how I can change it to avoid the use of the while statement 'cause when it enter in this loop all the game stop and waiting for the loop to finish
Select the asset and either drag it to the desired destination if you want to change its direction, or copy it by pressing Ctrl + C, selecting the desired destination and pressing Ctrl + V.
If you want to select multiple assets,
- Click on the every single asset with
Ctrlheld, or - Click on the first and last assets with
Shiftheld
how do i change direction
Have you read my message?
like for example the second tile i want to make it face a different direction
Oh, direction
For some reason I have read it as "destionation"
its ok
I don't think you can do it directly in Unity. Simply do it in your own sprite editor and consider resizing the canvas to then slice them with the Multiple sprite mode for convenience
ok i guess i can do that
but unity should add this
I can't use coroutine so I used async
You can indeed use aCoroutine, have a look on the method you're using.
yield return www.SendWebRequest();
Unity has an option to flip an image in the SpriteRenderer
can you make a code for vr crafting
Both vertically and horizontally
yo i can maybe try this
thanks
Note that this doesn't change the original sprite
This isn't UnityGPT
oh haha
No I can't use coroutine x) my class doesn't heritate from Monobehaviour
ok thats good
You can start a Coroutine on some kind of a Singleton, which doesn't get destroyed
Or on any other MonoBehaviour reference
I just can't 'cause of my script system but I found a solution, I just removed the while loop and just await Task.Yield(); and it works fine so yep... I don't know if it's a good use
Dangerous, the request might not have finished after a single yield
Depends on the computer and IO speed
await Task.Run(() => www.SendWebRequest());
yeah that's what I supposed
ow that's seem good
ouch
What about this?
await Task.Run(() => www.SendWebRequest()).ConfigureAwait(false);
same
Does your initial code give the same error?
Then you just cannot await the web request
Consider either using your initial code or the coroutines then
there is no possibility to just change the initial while loop ?
Have you tried with delaying the task? await Task.Delay(delayMilliseconds)
Oh, this is not what you mean
The best way would be to use a combination of TaskCompletionSource and subscribing to the request's completed event
for (int i = 0; i < i++;)
What about this one?
I feel like it should compile
Although start from -1
for (int i = -1; i < i++;)
this will loop forever no ?
Sure
Oh, have just read your code
I thought you just wanted to print i
Why can't you do it in a while loop?
'cause I don't really know why but in unity when you enter in while loop all the game is paused while you're in the loop
It would look something like this:
TaskCompletionSource<AudioClip> tcs = new();
using UnityWebRequest www = ...
www.completed += () =>
{
// get clip
tcs.SetResult(clip);
}
www.SendRequest();
return tcs.Task;
I don't ever worked with that thing, I will try
Oops the completed event is on the operation, not the request, so you need to send it then subscribe on that. But the structure is roughly the same
ooooooooook I'm missing a thing ^^'
See above
yep but like I said I'm not familiar with this system (I have to learn it, it seem very usefull)
The completed event is on the operation variable, not on www
var operation = www.SendWebRequest();
operation.completed += operation => {
}
ok
Yep, it passes the operation itself in the lambda argument, so you can't use a empty parameter list () =>
oooook it seem good and what it's returning exactly ?
Well, you need to move the old code that downloads the clip inside that lambda first
The DownloadHandlerAudioClip.GetContent() one
ok that's good
And then change your method so it's an async Task<AudioClip>
And you should be able to do AudioClip clip = await xyz.LoadAudioClip("path", type)
Oh don't mark it async my bad
oh or can I just write return tcs.Task.Result;
Or you return await tcs.Task and leave the method async, your choice
No don't, this blocks the thread waiting for the task to complete, eliminating all usefulness of async
oh ok
go testing
oh ok no
that's my fault
I've just passed wrong param
yeah it works !
thanks bro !
Just what this system is called for that I search on internet to learn it ?
C# TaskCompletionSource will get you most results
ok thanks !
why do I get the error "SetDestination" can only be called on an active agent that has been placed on a NavMesh. when It's clearly on the navmesh ? is there a fix to this ?
Read the stack trace of the error to find the offending line of code. You are probably calling SetDestination on a prefab or something
nope, I'm calling it inside a component that has a reference to the navmeshagent
Yeah but which navmeshagent
it's likely a reference to the wrong one
there is only one
SHow us
show us what the code is referencing, and how you got/assigned that reference
can you scroll all the way up to the top of the console window?
Basically in the old days where async/await wasn't broadly implemented, most of the code base used something like Unity uses today, where you had BeginXYZ() and EndXYZ() methods that were to be called to start/stop the "async" coperation, along with an event to signal when the operation was completed.
When async/await was introduced, a whole bunch of types like Task were introduced for the new methods, but the old ones still existed. To bridge both worlds while Microsoft switched to the async/await pattern, devs used that TaskCompletionSource class to "convert" the Begin/End pattern into methods that could be used with async/await.
Exactly, you can see in the first photo it is clearly right on top of the navmesh
Actually I can't, because you have this set to Center
It should be set to Pivot to know where the object actually is.
ok I see, very interesting
pivot is at right at the enemy's hands (they are touching the ground) and in the picture you can %100 see that the agent is touching navmesh
@leaden ice
sorry for tag forgot to reply
and with pivot selected :
I'm not an expert on NavMeshAgent exactly so I'm not sure of the intricacies of what might be going wrong here
This might help https://forum.unity.com/threads/failed-to-create-agent-because-it-is-not-close-enough-to-the-navmesh.125593/
I have a large terrain with a navmesh, running on an authoritative server running Unity 3.5 and uLink. Everything works very nicely, but when creating...
Also are you generating the NavMesh at runtime @olive harness ?
no, it's generated beforehand
weird, I'll update unity maybe it'll fix it
can i learn c# while learning unity c#? like, would i learn c# while making platformer without knowing c#? (i wish)
I think it's better to know C# beforehand, but yes you can learn both at once. Many people do.
yaaayyy
don't rejoice too much, trying to code in Unity without knowing at least the basics of C# will make your life so much more painful
i think i know very basics
thanks anyway
If you have moderate programming experience, you can pick them up together.
im not moderator ๐ฐ
oh, moderate
I did, but eventually did an IT study for mainly c#.
So it's still wise to learn c# outside of unity
very sensible. A good grounding in C# will make your learning experience in Unity so much easier
My very first interaction with c# was a tower defence tutorial from Brackeys.
The problem with focusing on unity alone is that a lot of tutorials won't teach you helpful and sometimes important aspects of C#
For example: Extention methods
this is a common falacy. Tutorials don't 'teach' shit. They show one way of doing one specific thing. Nothing more
They help (me) understand the functionality of a certain aspect.
If I were looking into animations, I search up multiple tutorials to show me how I could implement stuff and based of the info I experiment
And end up in more stackoverflow pages
then you are taking the right approach. Most people copy verbatim and understand nothing
video tutorials where you just copy down code from the screen could be replaced with a .unitypackage
๐ผ
that is what passes for 'learning' nowadays. No actually brain or thought required
i've been thinking about creating a tutorial series that's more concept-oriented: e.g. a video or article that explains the concept of GameObjects and Components
unfortunately that does not instantly give you a working game
and i can't put "IN JUST FIVE MINUTES" in the title
yeah, no 'quick fix', no audience
on the other hand, it would be significantly more useful for people who are actually interested in learning
how do you make diffrent particle for a gun by hitting diffrent layers?
so sparks when you shoot a metallic surface, dust puffs when you shoot dirt, etc.?
this is going to be very similar to making footstep sounds for different surfaces
Make a script like:
public class Surface : MonoBehaviour {
[SerializeField] ParticleSystem bulletImpactPrefab;
public void Hit(Vector3 position, Quaternion orientation) {
Instantiate(bulletImpactPrefab, position, rotation);
}
}```
And assign it to each surface
And in your shooting code, grab this component from what you hit and call Hit on it
ok thank you!
Another option is to use tags
Why do this on each surface?
so you can configure the impact behavior on each surface as desired
The first thing I thought of was to make a mapping of Material -> ParticleSystem that you store on the weapon
But this has a few problems...
RaycastHit can't tell you which sub-mesh you hit (mesh colliders have no concept of this, or of materials in general)
you could look for a mesh renderer on the thing you hit and ask it for its main material
but since materials get instantiated when you access .material, you'd have to access .sharedMaterial instead
To be clear there are many different ways to do it
If I were to do something I'd make a scriptable object that stores a dictionary<int (layer), gameobject> and when hitting a gameobject it would compare and spawn based on the layer
I like this idea the most.
I would use a simple script that just holds the enum of your ground type. In your raycast just check for that element and according to the enum, spawn / play the desired particle system.
It avoids tying your impact effects to other weird stuff.
It could be a problem if there's a huge number of objects in the scene and/or if you need different submeshes of objects to have different impacts like you were saying
but yeah
it's modular
I'm not a fan of using layers, because that means you're eating up a lot of layers just for impact effects
oh certainly
you want to use layers for conceptually different things
Think you can do approach similar to "physics material"
Differnt sound, impact particle, etc
Yep exactly
I'm having trouble expressing this, but you have to watch out for..."invalid relationships"?
Situations where it looks like X and Y go together, but then it later turns out that they don't
they just happened to fit together in most cases
XY problem? ๐ค
like, not every object with "Metal" in its name should make a spark when you shoot it, so using the object's names would be bad
nah, I just picked X and Y as two random variables
(and some objects not named "Metal" would also need sparks)
and looking for the material on the object you hit would be problematic
you might have colliders on child objects that have no renderer
I mean.... with your component approach you can just make a script what pools the objects with the same scripts right?
Usually: make designer assign correct one ๐
i'm not sure what you mean here
Not my fault โข๏ธ
if you mean pooling the particle systems, then yeah
Yeah 
is it possible to take the unity standard human rig and seperate it to make a rigidbody based movement system?
i tried playing around with it but I have no idea what im doing
or is there a humanoid that comes unrigged
Rigging is about animation
nothing to do with character movement systems
yeah I meant i want one without builtin animations, just the individual parts
You want one what
a person/humanoid
Check the Unity asset store for a free model
But what do you mean by "standard human rig and seperate it to make a rigidbody based movement system"
You mean instead of a single deforming skinned mesh, you want a bunch of separate object meshes for individual body parts?
What's your goal
I think so
For what reason
to make a custom movement system for fun
Is it because you can't figure out how to use a normal animated skinned mesh?
this is ill-defined
sorry
I'm trying to figure out the link between "custom movement system" and the mesh
Normally these are completely unrelated
or mostly unrelated at least.
Are you talking about making something QWOP-ish, where you move a character by moving their individual limbs?
If so, this has nothing to do with rigging. You're just moving the armature with physics instead of an animator
ok thanks everyone ๐
Is there a way I can decompose a Quaternion into rotations around a set of axes? Imagine turning one Quaternion into three sets of angle-axis values (where I provide the axes).
I am writing code to rotate a character's eyes. I want to limit the amount of rotation around the left-right and up-down axes. In the image above, I'd want to limit rotation the red and green axes.
It's not so simple as just limiting the local euler angles, since rotating around one of these axes winds up changing all three of the eye's X/Y/Z local euler angles! I am also not a fan of messing with Euler angles in general, anyways.
I've wanted to do this kind of thing in many other situations, so even if I find another way to handle this, I'm still interested.
I was thinking of using the quatertnion to rotate a vector and then using FromToRotation to figure out some rotations, but this is going to lose the roll
public void RotateObjectToFaceAway(Transform obj, Vector2 position)
{
float outerAngle = position.x * 2f * Mathf.PI;
float innerAngle = position.y * 2f * Mathf.PI;
float outerRadius = torusRadii.x;
float innerRadius = torusRadii.y;
Vector3 outerRingPosition = new Vector3(Mathf.Cos(outerAngle) * outerRadius, 0f, Mathf.Sin(outerAngle) * outerRadius);
Vector3 innerRingOffset = new Vector3(Mathf.Cos(innerAngle) * innerRadius, Mathf.Sin(innerAngle) * innerRadius, 0f);
Quaternion torusRotation = Quaternion.Euler(0f, -outerAngle * Mathf.Rad2Deg, 0f);
Vector3 finalPosition = outerRingPosition + torusRotation * innerRingOffset;
obj.localPosition = finalPosition;
Vector3 direction = (outerRingPosition - finalPosition).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction, Vector3.up);
obj.localRotation = lookRotation;
}```
I am trying to position meshes equally spaced on the surface of a torus, with rotation orientation on the XZ to be up away from the torus and rotated around the ring O inner part.
I have it 99% of the way there but for some reason the cubes at the highest point and lowest in the Y axis alone don't get the correct rotation vector (as shown selected in orange).
Can you see why this is occuring? I haven't been able to debug the cause, I am assuming the issue has something to do with Vec3.Up that its not able to orient correctly because the direction is perfectly straight up/straight down?
yeah, if you use LookRotation where the direction and up-vector are identical, you won't get good rolls
What would you suggest in place of lookRotation? 
I think you still want LookRotation, but with different inputs
I can do something other than it if for sure
adding some Debug.DrawRay calls will help visualize what's going on
it looks like direction points from the center of the toroid ring to the position of the cube. Is that right?
I think so? It's tough for me to verbally describe a torus because its all circumferences, when I say 'ring' or 'center' its ambiguous if I'm talking about the Macaroni center (purp) or planetary center (yellow)
My first thought is to replace Vector3.up with one of the toroid's tangent vectors. It'd be the tangent that walks around the ring like this
i also need to figure out the vocabulary...
for a cube on top of the torus, you'd get these vectors
it would look in the direction of the long vector with the short vector as the "up" vector
You should be able to compute this with...
actually, I need to think on that for a sec
you'd be rotating the direction vector around the camera axis here
by 90 degrees
You're looking for the direction the disc is going
Vector3 tangentVector = torusRotation * new Vector3(-Mathf.Sin(innerAngle), Mathf.Cos(innerAngle), 0f);
Vector3 direction = (outerRingPosition - finalPosition).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction, tangentVector);
You nailed it already, this was it
Which you can compute much like the actual position -- it's just a phase shift of 90 degrees
nice!
By getting rid of all of world-space vectors, you wind up with something that works at any orientation
i've been trying to clean this kind of thing up in my game, so that when I start doing weird stuff, my old code doesn't break
assuming that world-up is always your up works until it doesn't (:
Yeah ๐ซ
actually getting that tangent can be a major problem for more complex situations
I am going to animate this later on, trying to build up towards something like, so likely I'll be back when that blows up
positioning and rotationing is step 1, next is moving it
You might want to write a function to calculate a set of basis vectors for any point on the torus
you'd have:
- normal
- outward tangent
- circular tangent
(you already have two; just cross-product them to get the third one)
i may have drawn the third vector backwards
this is just another coordinate space, much like world-space or local-space
Ooh okay yeah that makes sense. Ill refactor my direction codes out of the rotation method into standalones that can be called
it's way easier to reason about problems when you're in the right space
torus-space
you can either compute world-space vectors for each of these things
or you can figure out how to convert back and forth between world-space and torus-space
actually this just made me remember:
A 2D map that loops NS and EW is a torus ๐ค
the latter would be nice: [1,0,0] would be a normal vector when converted back into world space
I am a little murky on how you do that -- it's a https://en.wikipedia.org/wiki/Change_of_basis
If you have three vectors and an origin, you should be able to bash together a transform matrix..
Ah, you could use Quaternion.LookRotation to create a rotation out of two of the vectors, then combine that with the position with Matrix4x4.TRS (it takes a position, rotation, and scale) https://docs.unity3d.com/ScriptReference/Matrix4x4.TRS.html
I should try that out
Once you have a Matrix4x4, you can use it to transform to and from torus-space
basically anything you can do with a Transform
Ill have to think deeply on this. I am good with logic but algebra, math transformations are my weak point
I don't see a TriggerColliderScript anywhere in the second screenshot
Yeah looks like you have two different classes defined in this file?
three of them actually
yup exatly
well - why did you do that
Each script needs its own file
and he one shown is not the one you attached to the object
one for each triggerCollider! I need logic for each triggerCollider
you really don't
but that's a separte topic
the main issue here is you can't have multiple MonoBehaviours in one file
and code you wrote in one class has no bearing on the other class
ok... So how can I have different triggersColliders in one script?
You have a CS_Baliza attached to the object. The code in TriggerCollider1Script doesn't affect CS_Baliza
you don't define more than one MonoBehaviour class per script file
I don't understand what you mean by that reallky
yes I know
what are you trying to do?
and adding something to one class doesn't make it show up in another
THis is the wrong way to do whatever you're trying to do.
I gues you're saying you have multiple colliders on this object and you want each one to do something different when it triggers with another collider?
YOu would do this:
- Move the colliders onto child objects
- Attach a script to each child object to handle their OnTriggerEnter behavior.
And when you write multiple scripts you have to put them in different files.
so what I need is:
I am making a "checkpoint" like for a racing game, and the vehicle has to enter in the right direction on the "balizas" so my idea was: Use a triggerCOllider to check if it can trigger the second and check the checkpoint
the colliders already are on different child g.o.
then put the separate new scripts on each child object
I just didnt want to have 2 scripts...
but you already did. in fact you wrote three
yes i guess...
did you read the error message
Look at the full stack trace of the error and go to the offending code and fix it
i didn't touch any script i was doing my gui
it explains the problem
show the stack trace
ah, see the stack trace then
your index is bigger than the list size.
or negative
you are just guessing
how can i fix that ? i didn't code anything i just added a ui images and text (also i'm a beginner i don't know much about unity)
nop I just fix the same exat code msg on my project
EDIT: I think i awnser wrong statement XD
you have not shown us the stack trace. please show us the stack trace
it appears below the error in the console when you have it selected
Tell that to someone that coded it
yes you are, you have no idea if this is even caused by one of his objects
show the stack trace like you have been asked to, twice
what is stack trace ??
No other way to answer it, unless the op provides more information
Click on one of these error messages
And paste it here
it's the bit at the bottom of the console when you select an error
The stack trace shows the full way to your error
yes, Unity bug, restart your editor
looks like the renderer threw up. that's not your problem
as a rule of thumb: if you don't recognize anything in that stack trace, it was a problem on Unity's side
can i add a disabled component to the object
or add and then disable, before component calls Start()
yes, although Awake will be called
Start is called just before the first Update is invoked, so you should be fine with adding and disabling.
don't care about awake
should i? can it be that disabling happened after start, like cuz system lagged?
Hey, I'm trying to create an atlas v2 through script. Basically what I'm doing is:
var atlas = new SpriteAtlas();
atlas.Add(spritesArray);
AssetDatabase.CreateAsset(atlas, "Assets/SomeName.spriteatlasv2");
But doing so causes a native error to appear saying that this extension is not supported. Removing v2 from extension lets me create atlas, but it's a v1 one. I've searched everywhere, but couldn't find a way to create v2 atlas through code, any ideas?
well, maybe some async shit going on
why do you think this is happening?
just curious
so you aren't actually having a problem
im testing a thing out rn
If "system lags" then the whole unity event cycle stops. There's a clear order in which everything happens, event async operations
https://docs.unity3d.com/Manual/ExecutionOrder.html
You'd have to be genuinely running things on multiple threads to get this sort of thing
and other threads aren't permitted to touch most of unity's data
well, everything works
trying to measure if runtime terrain spawning + grass zone spawning causes lag spikes
and well, it certainly does
well, terrain mesh instantiation doesn't actually consume much fps
var results = new NativeArray<RaycastHit>(totalCount, Allocator.TempJob);
var commands = new NativeArray<RaycastCommand>(totalCount, Allocator.TempJob);
for (int i = 0; i < totalCount; i++)
{
commands[i] = new RaycastCommand(RandomPoint(), Vector3.down, QueryParameters.Default, transform.localScale.y + 0.02f);
}
JobHandle handle = RaycastCommand.ScheduleBatch(commands, results, 1, 1, default);
handle.Complete();```
alr i found my fps eater
this is one place where you can kick things onto another thread for a bit (:
note that the game will stall the next time it tries to update physics if a raycast command is running, iirc
can i somehow prohibit object from updating unless jobhandle is complete
I use raycast commands to batch up a bunch of work for my game's vision system
Is there a way to deactivate collision forces push between to dynamic bodies but still having the oncollisionenter proc? Or making a collider trigger but still standing and not falling off the ground?
that's what happens. the game freezes until handle.Complete() returns
so well, can i freeze the object and make it wait until thread with handle is completed
not the entire game
but just the object
in 2D, yes, you have forceSendLayers and forceReceiveLayers in the newer versions of Unity. I don't think 3D has such a thing
you could check if the job handle is done and skip the rest of Update if it's not finished, I guess
the entire update in my case
you'd want to get rid of handle.Complete() (and store a reference to the JobHandle in a field so you can check it later)
well, i call this method single time per object
i'd prefer some way to deactivate object or component until thing is done, but disabled stuff doesn't call update anymore
i don't even need the component until job is done
doesnt exist? im in a really new version btw
checking handle.IsCompleted at the top of Update and returning early if you get a false is roughly equivalent to disabling the component
It's an instance property, not a static property
it won't show up like that
get the component from object and search there
you need a Collider2D variable
is there any place to check the different parameters i can send to the method or how does it works?
here they dont show up
it's a LayerMask property, not a method
can i dispose commands array before job is finished
No, because then you'd be throwing out the data the job is working with
You have to keep those around and then dispose them when the job is done
feels bad sadly
i need to keep the job reference, the command and results arrays, as well as some other stuff
on each component
and also for each component do if checks each update
while components amount might get to like 1000
idk if it's gonna affect fps
Okay and how can I avoid duplicating Code? I have some variables and methods repeating in some enemies, but then I have other variables and other methods repeating in other enemies and the player, so I cant use inheritance because that would make a huge tree. Interfaces also are not an option cause they still force me to duplicate code
wdym you can't use inheritance
enemies and player are surely inheriting some kind of "LivingEntity" class/interface
you're looking for composition
instead of making a bunch of classes like EnemyYouCanShoot and EnemyYouCanShootWhoCanFly, you make simpler components
for example, an enemy's locomotion -- how it moves around -- should be separate from the logic for making it explode when it reaches 0 HP
So I make a class, instantiate inside the player and just take whatever I need?
Dependency injection would not be a good option?
dependency injection is a separate topic
here, have a look at one of my entities
Would u make a class containing everything the enemies / player would have in common then fill in the rest in their own file? Then in their custom file u can call on this class with its peramaters, sprite, move speed, health, etc.. then add in the custom variables and functions for that specific enemy?
i should have split this into several game objects
this is an entity I use for benchmarking my vision system
the Entity component glues all of the other components together
it has an Empty Brain component that does nothing and an Empty Locomotion component that also does nothing. These could be replaced by more complex components to let the entity make decisions and move around
It has a Vision component that lets it see, and a Visible component that lets it be seen
I didn't have to create a new VisionBenchmarkEntity component to make this work
assigning references in the inspector is a form of DI, so you're already doing it (:
Are these built in unity stuff or did you make custom icons
i know it better than Illustrator lol
the icons are meant to represent how an Entity contains Modules
Modules are pretty much just ordinary components, but the Entity calls Update/LateUpdate/etc.-esque methods on them manually so that I can better control the order of execution
and I can ask the Entity for Modules instead of having to do a GetComponentsInChildren call
Does the main entity subscribe to the components or do the components subscribe to the main entity
I got my answer
Interfaces are cool. Not sure I'd call them a form of DI though
interfaces on their own are not a form of dependency injection, however many DI frameworks typically expect you to inject interfaces
much cleaner with interface so you can switch up the implementations
I spread mischievous partial misinformation
the "Brackys" route
Do you really need DI tho ?
it really seems like you are confusing the concept of dependency injection with DI frameworks. you can do DI without some bloated framework
for example, assigning references in the inspector is a form of DI
I guess
you don't need to ever do "DI" or SOLID is just helps keeps stuff clean
literally just passing an object to a method or an object ctor is DI
if i use composition and i declare for example the class into the other class in the inspector the variables from the class that is getting declared in the other one will appear?
And also, I cant figure out how to use forcesendlayers
I can't really parse this question
If you do this...
wdym how to use it? it's a property that you assign a LayerMask to
public class Foo : MonoBehaviour {
public Bar myBar;
}
public class Bar : MonoBehaviour {
public int stuff;
}
then you'll get a "My Bar" field in Foo's inspector
an interestingly now the recent .net frameworks for DI use the "Singleton" extension method
you can drag a Bar into it
as i somewhat-sarcastically say, 2 + 2 is DI
i injected 2 and 2 into the operator function
Both mono?
and how do i assign it?
=
are you asking how to set up the layer mask in the inspector?
you wouldnt be able to assign in inspector otherwise
I've used [serialized]
Thatโs fine since it is singleton in that specific context, not static for program lifetime
And it works
If Bar is a plain-old class and not a MonoBehaviour, and you mark it as [System.Serializable], then it will appear in Foo's inspector
I serialized the class and can assign in inspector
And since it's not a unity object, you'll see its values directly there
rather than needing to assign a reference to a Bar somewhere else in the scene
no, just how to make the collision of an enemy only apply the oncollisionenter code and not the force, because if the force is applied after dashing and im inside the collider i will go down the floor
isnt that the Lifetime of the program? interesting one is the "Scoped" as it scopes within the session rather than program lifetime
Maybe I'm just too used to working with aspnet recently ๐ค
and you said i need to use the forcesendlayer for that
If you have multiple server or test running, there would be multiple of those 'singleton's
behold: the multi-singleton
oh multiple. I mean 1 server app
singleton't
yeah, i have a boss which is like x3 size of my player. The boss has a dynamic body, same as my player, so when i dash into him (which the dash ignores collision with all enemies until it finishes) and the dash finishes, if im inside his collider i will get pushed underground
and eveything is in 2D yeah
Just Single (there aren't a ton)
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-8.0#service-registration-methods
Still trying to remember when to use Scoped, Transient vs Singleton ๐
so like playerMask = forceSendLayer? doesnt work
Even with that it is meaningful that you can run tests and can expand to multiple context if required
I presume you've used = at least once before...
it assigns the value on the right into the variable on the left
A layer is not a mask
ok i think i got it
Yeah very web focused categories tho
haha yeah me working on a custom backend for a unity project 
so in that photo your making the layer of the object that has that collider apply to the layer of the playerLayer right?
this is reading the forceSendLayers property of the collider and storing it into playerLayer
it does nothing else
notably, this does not change which layers the collider sends force to
so if i want to deny the collision forces between 2 dynamic objects to interact I cant?
you can, but not by writing whatever that code is
perhaps you want https://docs.unity3d.com/ScriptReference/Physics2D.IgnoreCollision.html instead. It allows you to ignore collisions between two specific colliders.
You could give the player some extra time to get out of the boss's collider.
I use this a lot but wont work for this because i want the onCollissionEnter method to proc but not the forces between the dynamic objects to get applied
like if it was a trigger but without it being a trigger
okay, then you need to update either the forceSendLayers of the boss's collider or the forceReceiveLayers of the player's collider
To make this easier, I would add two LayerMask fields: one for the normal state and one for the "ghost" state
Me turning on my PC knowing I have to rewrite my whole procedural melee swing code because it's too limiting for me to use 
the first one should have every layer included
the second one should have the player's layer excluded (if you are doing this on the boss) or the boss's layer excluded (if you are doing this on the player)
this is a channel for code questions not random ramblings
Oh wait yeah I forgot there were other channels ๐
I think forces can even be deactivated in every enemy since i dont need them, the thing is idk how to deactivate the force
because i never used that force layer thing
then just assign playerCollider.forceReceiveLayers exactly once in Start or something
if you don't know how to do this, ask about it instead of skipping past it
How can i draw a set of meshes with random colors while reducing batch count?
Unity tilemaps is able to do this, but I dunno know
in here forces are the same, what would it change if i swap layers and both apply forces
I don't understand this statement
Are you asking about whether you need to configure the force layers on both the boss and the player colliders?
No no, I think i might be understanding wrong your explanation but playerCollider.forceReceiveLayers makes the game just to receive force from the layers you design right?
So you need to go 1 by 1 declaring each layer?
That property is a LayerMask.
it lets you include or exclude all 32 layers
you need to add a LayerMask field to your component and set it up in the inspector to include the correct layers
I think tilemaps bake the color into the vertex data. Don't quote me on that one, though..
okay give me a sec im gonna try
okay done, I am stupid sorry, wasnt understanding correctly
You are insane โค๏ธ
btw one last thing, if in the player start i just set that i can receive the force from none layer and in the start of the boss i send force to the layer of the player, at the end the player would receive the force cause im sending or it will just get bloocked because i set it up to none receiving? Imagine that both codes run at the same time
The sending collider must want to send force to that layer, and the receiving collider must want to receive force on that layer
see here
so if i want to let everything at it is when i set up the layerMask i need to check every layer box except for the one i dont want to apply it right?
correct
Now I have another issue. I have a prefab for the player. On each scene i dragged a prefab of the player but when he is already in the hierarchy i changed some values cause i want him on some scenes with more hp than others. Now If I want to add something new to the player and apply on all of the gameobjects but without overriding the stuff that i changed for each of them, is there anyway? Or should I set it up in other way so i dont have this problem?
Each prefab instance will keep its overrides.
so if the prefab instance overrides "foo" to be 100, changing "foo" on the prefab will do nothing: you'll still have a value of 100 on that instance
so if i add something new with a certain set up directly to the prefab all the other values will remain the same on each gameobject?
why my enemy is taking the last position of my player to chase him instead of contiously updating
at start my enemy goes to the first position from the prefab and then i stays stuck there.
Because you never update the target position for the enemy. You've answered your question in your own second message.
okay now i have another problem, i can move the enemies when i hit against them, before i couldnt
correct; changing one component won't make every instance forget all of its overrides
that would be useless!
since you no longer receive force from enemies, you're no longer pushed away when you walk into them
but that doesnt explain why i can push them
I dont want to push them
and i only added the receive boxCollider.forceReceiveLayers = layersForced; statement so i shouldnt be able to push them
enemies can no longer push you away
therefore, you can overlap the enemy
therefore, you push them away
and to stop that from happening what can i do, i dont want to push the enemies
using the receiveforces has any other secondary effect?
If your problem is that the player is ending a dash inside of enemies and thus getting forced out suddenly, you should really just use IgnoreCollision
You could add a second trigger collider to the player that detects when you leave the enemy's collider, so that you can turn collision back on
if i use ignorecollision the enemy cant hit me with his collider
and the problem is not getting forced out, thats what i want, the problem is that i got forced underground not to the sides
Few ways to go about this and ideally you just bake/reconstruct the whole mesh together with the vertex colors chosen at uv coordinates. Or, use sprite renderer and use its dynamic batching if you're using 2D
srp batching does work ok too if you do want to change via fragment and that you're using a single shader, but if you're not reconstructing/moving the meshes, then go with the bake solution
with chunks if large enough
I see, so instead of updating colors via the shader, we update the mesh colors directly
I used animation controller, and the player movement code is making the transitions possible
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
@heady iris the receiveforces has any secondary effect apart from the player pushing the enemy? And btw is there anyway to edit a tilemap without getting lag? I have a lot of tiles and its really laggy and a lot of times starts loading pop up, but if i edit in prefab mode each time i do something it also gets the pop up with the import
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerProjectScript : MonoBehaviour
{
protected Animator _animator;
protected float _movX;
protected float _movY;
// Start is called before the first frame update
void Start()
{
_animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
_movX = Input.GetAxis("Horizontal");
_movY = Input.GetAxis("Vertical");
_animator.SetFloat("X", _movX);
_animator.SetFloat("Z", _movY);
if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
{
_animator.SetBool("Shift", true);
}
if (Input.GetKeyUp(KeyCode.LeftShift) || Input.GetKeyUp(KeyCode.RightShift))
{
_animator.SetBool("Shift", false);
}
if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl))
{
_animator.SetBool("Crouch", true);
}
if (Input.GetKeyUp(KeyCode.LeftControl) || Input.GetKeyUp(KeyCode.RightControl))
{
_animator.SetBool("Crouch", false);
}
}
}
if you want to use a rigidbody you should not move using Root motion / animation
How should I move?
using the rigidbody
How can I animate a character that has gravity and a collider?
with the same way you're doing it now ?
but just switch movement to rigidbody..
if you have to switch the animator
I found a solution right now. Instead of using the rigid body, I used a character controller. It's working!!
Thanks for the help!
Hey, I have this method, which calls a version of WaitForSeconds according to the code running in the Editor or not. Is there any way to implement a class the same way?
yield return AwaitForSeconds(1f);
private IEnumerator AwaitForSeconds(float seconds)
{
yield return
#if UNITY_EDITOR
Application.isPlaying ? new WaitForSeconds(1f) :
#endif
new EditorWaitForSeconds(1f);
}
And my 2nd question would be about a better name for it
And what exactly are you trying to do with a class that would require conditional compilation?
But sure, you can do it, as long as you don't break something obviously
make a class that implements IEnumerator. Calling MoveNext should return true exactly once, and when it's called, you should set make Current be the (Editor)WaitForSeconds object
Unity offers this:
https://docs.unity3d.com/ScriptReference/CustomYieldInstruction.html
You can derive from this class
Editor Coroutines would've probably implemented this in their code, had it been possible
Do they not?
I feel like I'm missing some context for this question
Yeah, EditorWaitForSeconds is a completely different class with no parent.
namespace Unity.EditorCoroutines.Editor;
public class EditorWaitForSeconds
{
public float WaitTime { get; }
public EditorWaitForSeconds(float time)
{
WaitTime = time;
}
}
This is its full version with just summaries removed
Just tested it out and it perfectly does what I need. As usually, thank you for a perfect solution ๐
Note that this will produce just about as much garbage as using an IEnumerator method
you can make a struct that implements IEnumerator, but it'll get boxed when it's returned as an IEnumerator
if i have animations setup like the image, I should be able to play these animations with this code, right? ```cs
GetComponent<Animation>().Play("V_MoveLeft");
well, you capitalized it wrong
i don't use Animation (it's an ancient component) but that's probably not helping
sorry i got boomer eyes haha
ah its a project that was already setup, trying not to change a lot of stuff.
thank you for noticing 
Hey my Unity editor isnโt installing. Itโs stuck on Editor Application please help.
Good afternoon. I'm trying to implement a black overlay on the camera when the player falls out of bounds and/or dies, in order to reload the current scene and reset the player at the last checkpoint. The issues I've encountered are as follows:
- If I attempt to use SceneManager to add multiple scenes, based on what I've read, the objects in the 2nd scene can't perform actions on the canvas and/or camera in the first scene so I can't force a black-box overlay in front of the current camera while the scene reloads.
- If I create a black-box overlay and put it right in front of the camera, it'll just disappear once the scene is reloaded.
Maybe my approach to this is incorrect but how can I obtain the following order of actions?
- Player falls out of bounds/dies
- Create death overlay
- Reload Scene
- Remove death overlay
My editor wonโt download
this is not a code problem
ask about your editor install in #๐ปโunity-talk
also, !install
- Make sure you have enough space including on
C:drive. - Check that it's not being blocked by antivirus/security programs.
- Look through the logs for a real reason why the setup fails they are pinned [here](#๐ปโunity-talk message).
If you still have issues, perform a clean install in another location:
- Install the Hub and Unity in a non-system drive or a clean new folder in the root of
C:drive. - Failing that use the recovery Refresh option or reinstall OS entirely then repeat the previous step.
You can just put a second canvas in the second scene.
adjust its sorting order so that it winds up in front
I've tried that but it doesn't seem like the scene manager is loading the 2nd scene, at all.
well, then that's the problem
you should figure that out :p
You might just want to put this "fader" in DontDestroyOnLoad
That is exactly what I've done
No need to deal with a genuine multi-scene workflow if this is all you'd be using it for
Is that ScreenFader just another game object with a canvas component on it? Or is there other pieces to implementing it that way?
Yeah, it's a canvas with a single Image on it
You realize that if UNITY_EDITOR is not defined it will yield return the EditorWaitForSeconds object right? I don't think this is what you want.
The conditional expression split across a conditional compilation directive is...a little too clever, yes
(you can use #else)
That doesn't even bother me Fen, it's saying that if this code is in a build do new EditorWaitForSeconds(1f) which will fail in a build.
right, I just wondered if that hid the error
perhaps. I skimmed the conversation after that code snippet and didn't see it mentioned anywhere so I thought it worth mentioning.
What would be the best approach to draw a grid that remains in the players face and only reacts to y rotation. so if I look up and down or tilt my head left or right it doesn't react.
I am using a fullscreen shader rght now. I created a variant of that and added the shader to a quad and made it a child of the VR rig. That works but the quad edges can be seen
"A grid" is really vague
could you explain that more
OK so for example, lets say you have a VR game where the player is a camera.
Player presses a button to take a photo and whatever is in the players view is snapped.
What I am asking is what if there was another button that would bring up the rule of thirds grid.
Its always in your view (forward).
if we are uses axis then it only reacts to y rotations of the players head. Not X or Z rotations.
Im trying to figure out the best way to implement this without using a quad
Hmmm why should it only react to Y axis rotation? That doesn't seem right to me. Doesn't the rule of thirds just have to do with the actual viewport of the camera?
Even if the camera is pitched or dutched
Maybe a bad example but the point is that I only want the grid that is shown in front of the player to always remain in front of the players forward but ignore x and z rotations. Just trying to figure out if I could do that with shaders
of course you could. YOu could also just do it with a simple script
Think I am wording my searches wrong. I have been trying to find information on how to do it so that I do not have to recreate my fullscreen render feature shader graphs
Just wanted to thank you for the idea, I was able to implement what you stated
Can someone help me figure out how to fix my inventory count problem? The problem is when the max stack size is reached (5) it goes into the next slot which is good, but instead of just starting the new slot stack at 1 it starts all the stacks with that item in it back at 1. Heres the code and some SS
InventoryManager:
using System.Collections.Generic;
using UnityEngine;
public class InventoryManager : MonoBehaviour
{
private List<Item> items = new List<Item>();
public Transform itemsParent; // The parent object that holds the inventory slots
private InventorySlot[] slots;
void Start()
{
slots = itemsParent.GetComponentsInChildren<InventorySlot>();
}
public void Add(Item item)
{
// Check if the item already exists in the inventory
Item existingItem = items.Find(i => i.itemName == item.itemName);
// If the item already exists and is stackable, increase its count
if (existingItem != null && existingItem.maxStack > existingItem.currentStack)
{
existingItem.currentStack++;
}
else
{
// If the item is not in the inventory or cannot be stacked further, add it
item.currentStack = 1;
items.Add(item);
}
UpdateUI();
}
public void Remove(Item item)
{
items.Remove(item);
UpdateUI();
}
void UpdateUI()
{
for (int i = 0; i < slots.Length; i++)
{
if (i < items.Count)
{
slots[i].AddItem(items[i]);
}
else
{
slots[i].ClearSlot();
}
}
}
}
InventorySlot:
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class InventorySlot : MonoBehaviour
{
public Image itemIcon;
public TMP_Text itemCount;
public Item CurrentItem { get; private set; }
public bool IsEmpty => CurrentItem == null;
public void AddItem(Item newItem)
{
CurrentItem = newItem;
itemIcon.sprite = newItem.icon;
itemIcon.enabled = true;
itemCount.text = newItem.currentStack.ToString();
}
public void ClearSlot()
{
CurrentItem = null;
itemIcon.sprite = null;
itemIcon.enabled = false;
itemCount.text = "";
}
public void HighlightSlot(bool highlight)
{
if (highlight)
{
// Highlight logic here
}
else
{
// Unhighlight logic here
}
}
}
I'd double check to make sure it's not just the UI displaying wrong first
Another thing to check is if your Item type is a class and therefore a reference type, and you're maybe reusing the reference multiple times in the inventory, but when you set the stack size for one, it sets for all, since there's really only once instance.
yea the UI is correct, all of them have their own text linked. Before this I was having the problem of each new slot that added the next resource would start with the max stack size
I am using a class but let me check if im actually making a new item
Item existingItem = items.Find(i => i.itemName == item.itemName);
// If the item already exists and is stackable, increase its count
if (existingItem != null && existingItem.maxStack > existingItem.currentStack)
{
existingItem.currentStack++;
}
else
{
// If the item is not in the inventory or cannot be stacked further, add it
item.currentStack = 1;
items.Add(item);
}```
Based on this code you're not making a new item
yea I think thats the problem, im just getting the info from the hit on raycast then putting it in inv from that
ALso I think what you're calling an "Item" here would be better named as Stack or ItemStack
so I need to check what im hitting, create a new instance of the item, then add it?
and it should contain like:
Item item;
int quantity;``` for example
Or maybe Item should be an enum or a string or perhaps a ScriptableObject
yea ive got an item class applied to each object
using UnityEngine;
using UnityEngine.UI;
public class Item : MonoBehaviour
{
public string itemName;
public Sprite icon;
public int maxStack;
public int currentStack;
public bool hasHotbarPrio;
}
is it not supposed to be?
Make it a ScriptableObject
ahhhhh I thought it really didnt matter so I went this route xD
then it needs to be attached to a GameObject? Which is extremely awkward
It matters quite a lot
yea I just attach it to the gameobject
Like all of this stuff except for currentStack is NOT instance data
it's like.. static data that defines the item
100% a use case for ScriptableObjects
Then how would I link the gameobject with the scriptable object?
Reference it in the inspector
Would I have a field to drag the prefab into the script so when I place the prefab it always is linked to it?
what prefab
like right now I have a cube that I call "Gold" with the Item class attached to it
Ok so.. when you make an inventory system, and items can exist in the game as well as in the inventory
you really need to separate the concepts of:
- The item data (name, icon, etc)
- The "in the world" version of the item (MeshRenderer? Collider? etc)
- The "in the inventory" version of the item (Pure data)
- The "in the inventroy UI" version (UI elements that draw the inventory data)
bullets 2 and 3 there should reference the actual data definition of the item, which can be a ScriptableObject
Alright im going to learn how to do this so Ill get back to ya
Hey, monos can work, but yeah usually you want to have it as data then insert it into a monobehavior wrapper when it needs to be on the scene
and seeing that you're doing stacking, it probably should just be data
Im watching this video and I see why scriptable objects is better than what I was doing but he still added an Item class to the prefab even after making a scriptable object that represented that prefab?
Likely for the mutable data?
Is he populating the item class with the data from the SO?
