#archived-code-general

1 messages ยท Page 330 of 1

leaden solstice
#

Things they do for consistency

vivid halo
#

Fair

leaden solstice
#

The Zen of Python

knotty sun
#

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

vivid halo
#

To be a pedant, following the convention of the community makes collaboration easier and more seamless.

knotty sun
#

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

leaden solstice
#

Unless you are working on C++ which doesn't have "official" convention

vivid halo
#

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

knotty sun
#

yep and no one gives a rats arse what you do

vivid halo
#

If I coded like an ape, I think people would help me less

knotty sun
#

what makes you think you don't?

vivid halo
#

I follow convention, use a linter, and I have seen my code from 6 months ago

heady iris
#

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

knotty sun
vivid halo
#

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

knotty sun
vivid halo
#

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

knotty sun
#

well, we still write device drivers in ASM and without them you wouldn't have nice new bright shiny toys to play with

vivid halo
#

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

knotty sun
#

like anything else, practice, practice, practice and a damn good memory

vivid halo
#

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

knotty sun
#

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

pine bobcat
#

Hello, sorry for interupting here but is there anyone who could help me with my scene colors?

#

I see only yellow color in scene

knotty sun
#

does not sound like a code problem

pine bobcat
#

I have no idea where to write

#

Im sorry

knotty sun
pine bobcat
#

Thanks

fallow quartz
#

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;
}
restive ridge
#

does gravity calculation differ based on whether im using root motion or not?

heady iris
#

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

fallow quartz
#

it just happens on the ones that goes in a rectangular way

heady iris
#

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

fallow quartz
#

yeah taking the direction calculate at the end of the fixedupdate seems to have fixed the problem

fallow quartz
heady iris
#

it's just less likely, since you are always moving straight towards the target

fallow quartz
#

how could it still happen if the direction is being calculated all the time?

fallow quartz
gray mural
#

Is there any way to move a YieldInstructor as IEnumerator?

#

It's confusing that it's not even derived from it

heady iris
#

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.

gray mural
#

I can't seem to be able to get the seconds from WaitForSeconds to await it

heady iris
#

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

gray mural
#

Yeah, and the seconds are internal

heady iris
#

You can pull them out through reflection, of course

gray mural
#

Oh, sounds interesting

heady iris
#

What are you trying to make happen?

#

Are you trying to recreate how coroutines run?

gray mural
heady iris
#

You'll have to do what Unity winds up doing: check if the value is a WaitForSeconds, an IEnumerator, a CustomYieldInstruction, etc.

leaden solstice
#

I think they have something like

if (e.Current is WaitForSeconds w)
heady iris
#

it's icky, but that's what happens when you're getting handed an object :p

gray mural
#

I'm trying to make a StartCoroutine method, which, #if UNITY_EDTOR, runs my method with asyncs, otherwise calls MonoBehaviour.StartCoroutine

leaden solstice
#

Just use async tho

#

It works same as coroutine if not better

#

Still runs on main thread (because Unity magic)

gray mural
leaden solstice
#

Yes

gray mural
#

There are 2 options

#

Which one are you referring to?

leaden solstice
#

not implementing a custom StartCoroutine method and simply using async instead of the Coroutines

#

Why they are separate options

gray mural
heady iris
#

Yeah.

gray mural
#

And, I mean, I don't think async should be used if we already have coroutines on run time

leaden solstice
gray mural
#

And Unity doesn't support .NET 6 for periodic timer

leaden solstice
#

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

fallow quartz
#

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?

lean sail
fallow quartz
lean sail
fallow quartz
#

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

knotty sun
tawny elkBOT
fallow quartz
#

but idk the diff

knotty sun
leaden solstice
#

Which was so long so discord converted it in file

fallow quartz
#

I must have do something wrong

shy knoll
#

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

leaden solstice
#

I think that is usually done with many raycasts as physics involved ๐Ÿ˜„

shy knoll
shell scarab
#
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?

leaden solstice
#

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.

shy knoll
#

thank you so much : )

shell scarab
leaden solstice
shell scarab
leaden solstice
shell scarab
#

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.

leaden solstice
#

Actually

#

You are rotating spawnPoint again with LookRotation to the spawnPoint

#

I guess what you want is simply rotation * Vector3.forward or something

shell scarab
#

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

leaden solstice
#

Multiplication order is ever confusing

shell scarab
#

well left hand side is the start rotation right hand side is the rotation you're "adding" to it

leaden solstice
#

But not when you multiplying with vector

#

๐Ÿ˜„

shell scarab
#

well that you just make sure the quaternion is on the left

leaden solstice
#

Anyways your rotation already has the rotation for the spawnPoint included

#

So technically you'd just want unit vector to rotate alongside with it

shell scarab
#

multiplying the rotation with Vector3.forward gives the same result as rotation * Quaternion.Inverse(spawnFacing) * spawnPoint and it's really weird

leaden solstice
#

That's normal

shell scarab
#

it looks like it's working but in the wrong way lmao

leaden solstice
#

Because Quaternion.Inverse(spawnFacing) * spawnPoint should be just forward vector

shell scarab
#

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?

leaden solstice
#

No spawnFacing you made was LookRotation to the spawnPoint

#

So "undoing" it should be just forward vector

shell scarab
#

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

shell scarab
leaden solstice
#

And what shows the spawnPoint here?

shell scarab
#

the yellow spheres, sorry

#

(0,0,0) is at the center of the green plane

shell scarab
#

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

leaden solstice
#

Like in local space?

#

๐Ÿค”

shell scarab
#

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!

limpid agate
#

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

shell scarab
#

in 3D space or 2D space?

limpid agate
#

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

naive summit
#

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

lean sail
somber nacelle
naive summit
# somber nacelle 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

somber nacelle
#

okay and have you confirmed that the code you've shown is actually running?

naive summit
somber nacelle
#

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

naive summit
#

But thanks for the suggestions lol

somber nacelle
#

second script in wrong GameObject
so then you did have an error in your console that you were ignoring

naive summit
#

But there were no errors in the console

somber nacelle
#

unless your spotlight is also named Human then you absolutely had an error that you were ignoring

somber nacelle
#

you would have received a NullReferenceException when attempting to call the PickUpFlashlight method on the player variable

naive summit
#

sorry im a bit new to coding in unity

somber nacelle
#

oh my god. if you literally have errors in the console then do not insist that you do not have errors in the console

naive summit
#

Okay

errant flame
rigid sleet
#

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

calm talon
#
[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

broken bone
#

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?

calm talon
leaden solstice
#

Unity is bit late for adapting modern C# anyways

broken bone
#

It says C# 10 .Net 6 on the cover?

leaden solstice
#

That's good enough, Unity uses, eh, C# 9.0

broken bone
#

C#10 would still work with C#9 mostly, though?

leaden solstice
#

Yeah most of it will work or easily converted

broken bone
#

Thanks @calm talon @leaden solstice :) Appreciate it

twin widget
#

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

frosty widget
#

PLEASE does anyone know how drag works in unity and how it's calculated? It's been driving me CRAZY

cosmic rain
frosty widget
# cosmic rain There are many ways to implement it. You'll need to share some more context and ...

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

cosmic rain
#

But I think it would be better to just adjust your jumping height/velocity, instead of introducing a drag for it.

frosty widget
#

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

cosmic rain
#

Sound like some very unreliable logic. Maybe avoid modifying the drag at runtime and find some better solution

frosty widget
#

should I be using drag to decelerate the player?

#

that is currently how I'm using it

cosmic rain
frosty widget
#

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

cosmic rain
#

The jumping can then control the velocity separately.

cosmic rain
# frosty widget 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.

frosty widget
#

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

frosty widget
#

also when does drag affect velocity? I have heard previously that drag apllies to the velocity only until after the body of fixedUpdate executes

frosty widget
tawdry fox
#

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".

cosmic rain
cosmic rain
tawdry fox
cosmic rain
#

Maybe record a video of what's happening first

tawdry fox
#

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

cosmic rain
tawdry fox
#

Trying to record a good angle.

#

Car like turning with highly reduced deceleration. Additive speed game.

cosmic rain
#

Car like movement/steering is pretty complex actually. There are a lot of counteracting forces involved

tawdry fox
#

yeag

#

Couldn't get a good video example sadly.

frosty widget
#

like, by using RB.addforce

cosmic rain
#

You could lerp(move towards or some other way) the velocity to 0 when there's no input

frosty widget
#

I see, thank you

tawdry fox
#

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?

dusk apex
tawdry fox
#

Well I fixed it. It was greater than.

#

And it's a coyote timer. Doesn't really warrant as much explanation.

spring creek
#

We know what coyote timers are, that doesn't explain in what specific way yours wasn't working though

tawdry fox
#

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"

spring creek
tawdry fox
#

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.

gray mural
#

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) { ... }
shell scarab
#

*I also don't know of a way, or I would have just told you

gray mural
#

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

shell scarab
# gray mural That's because Unity doesn't provide `Coroutines`, which can run in the Editor. ...

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.

gray mural
#

So Editor Coroutines package doesn't really fix anything

shell scarab
#

the editor coroutine package provides an "EditorWaitForSeconds" class which waits seconds in the editor using unscaled time

gray mural
maiden heath
#

[field: SerializeField]
what is the "field" thing in the code block above? why put it?

shell scarab
#

without the field keyword there it would try to apply it to the Property

maiden heath
#

what is this "property"?

shell scarab
# maiden heath 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`.
maiden heath
#

thank you for the explanation

gray mural
#

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 ๐Ÿ™‚

gray mural
prisma zephyr
#

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)

rigid island
tawny elkBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

prisma zephyr
#

it might be hard I'm French

cosmic rain
#

Have more confidence. Being French shouldn't be hindering your learning ability.

gray mural
prisma zephyr
#

I agree with you but I don't have much time it will take me years

gray mural
#

I would doubt that

#

If you're able to understand English you hear, you'll be able to use pathways

#

Also there're subtitles

prisma zephyr
#

Okay I'll try but my problem concerns visual studio, do they talk about it in there?

fallow quartz
#

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

tawny elkBOT
#
Visual Studio guide

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)

inland lance
#

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?

cosmic rain
inland lance
cosmic rain
#

Everything. Your initial message doesn't explain anything.

#

If it's hard to explain in words, record a video.

inland lance
#

alr give me a minute

cosmic rain
#
  • 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.
cosmic rain
inland lance
#

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

inland lance
cosmic rain
inland lance
#

yes thats the issue

#

i tried removnig the collision from mthe capsulle but it didnt change anyhting

cosmic rain
inland lance
#

give me a second to try that thank you

inland lance
#

again im fairly new to coding haha

#

this is my first project

cosmic rain
#

Check the documentation for raycasts. The method can take a layermask as a parameter. There should be examples too.

stoic ledge
#

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.

cosmic rain
inland lance
#

ok thank you

cosmic rain
#

!logs

tawny elkBOT
#
๐Ÿ“ Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

cosmic rain
#

Thought it's cleared every session, so keep that in mind.

light pond
#

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

inland bison
#

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

gray mural
gray mural
light pond
#

like for example the second tile i want to make it face a different direction

gray mural
#

For some reason I have read it as "destionation"

light pond
#

its ok

gray mural
light pond
#

but unity should add this

gray mural
gray mural
queen mantle
#

can you make a code for vr crafting

gray mural
light pond
#

thanks

gray mural
gray mural
queen mantle
#

oh haha

inland bison
light pond
gray mural
#

Or on any other MonoBehaviour reference

inland bison
#

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

simple egret
#

Dangerous, the request might not have finished after a single yield

#

Depends on the computer and IO speed

gray mural
inland bison
inland bison
gray mural
# inland bison ouch

What about this?

await Task.Run(() => www.SendWebRequest()).ConfigureAwait(false);
inland bison
#

same

gray mural
inland bison
#

nope

#

the initial code that I sent was perfectly fine, no error

gray mural
#

Then you just cannot await the web request

#

Consider either using your initial code or the coroutines then

inland bison
#

there is no possibility to just change the initial while loop ?

gray mural
#

I don't think so

#

Probably, just by creating your own method

simple egret
#

Have you tried with delaying the task? await Task.Delay(delayMilliseconds)

simple egret
#

The best way would be to use a combination of TaskCompletionSource and subscribing to the request's completed event

inland bison
#

ok I have a code that's working but ^^' it's very very very bad x)

gray mural
#

What about this one?

#

I feel like it should compile

#

Although start from -1

for (int i = -1; i < i++;)
inland bison
gray mural
#

Oh, have just read your code

#

I thought you just wanted to print i

#

Why can't you do it in a while loop?

inland bison
#

'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

simple egret
inland bison
simple egret
#

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

inland bison
#

ooooooooook I'm missing a thing ^^'

simple egret
#

See above

inland bison
#

yep but like I said I'm not familiar with this system (I have to learn it, it seem very usefull)

simple egret
#

The completed event is on the operation variable, not on www

inland bison
#

oooooow ok my bad

#

something like that ?

simple egret
#
var operation = www.SendWebRequest();
operation.completed += operation => {
    
}
inland bison
#

ok

simple egret
#

Yep, it passes the operation itself in the lambda argument, so you can't use a empty parameter list () =>

inland bison
#

oooook it seem good and what it's returning exactly ?

simple egret
#

Well, you need to move the old code that downloads the clip inside that lambda first

#

The DownloadHandlerAudioClip.GetContent() one

inland bison
#

ok that's good

simple egret
#

And then change your method so it's an async Task<AudioClip>

inland bison
#

ooooooook

simple egret
#

And you should be able to do AudioClip clip = await xyz.LoadAudioClip("path", type)

#

Oh don't mark it async my bad

inland bison
#

oh or can I just write return tcs.Task.Result;

simple egret
#

Or you return await tcs.Task and leave the method async, your choice

simple egret
inland bison
#

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 ?

simple egret
#

C# TaskCompletionSource will get you most results

inland bison
#

ok thanks !

olive harness
#

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 ?

leaden ice
olive harness
leaden ice
#

it's likely a reference to the wrong one

olive harness
leaden ice
#

show us what the code is referencing, and how you got/assigned that reference

olive harness
#

class is EnemyNavigator

leaden ice
leaden ice
simple egret
# inland bison ok thanks !

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.

olive harness
# leaden ice

Exactly, you can see in the first photo it is clearly right on top of the navmesh

leaden ice
olive harness
#

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 :

leaden ice
# olive harness

I'm not an expert on NavMeshAgent exactly so I'm not sure of the intricacies of what might be going wrong here

#

Also are you generating the NavMesh at runtime @olive harness ?

olive harness
#

weird, I'll update unity maybe it'll fix it

swift falcon
#

can i learn c# while learning unity c#? like, would i learn c# while making platformer without knowing c#? (i wish)

leaden ice
knotty sun
# swift falcon 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

swift falcon
#

thanks anyway

heady iris
#

If you have moderate programming experience, you can pick them up together.

swift falcon
#

oh, moderate

sterile reef
knotty sun
sterile reef
#

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

knotty sun
#

this is a common falacy. Tutorials don't 'teach' shit. They show one way of doing one specific thing. Nothing more

sterile reef
#

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

knotty sun
heady iris
#

video tutorials where you just copy down code from the screen could be replaced with a .unitypackage

sterile reef
#

๐Ÿ˜ผ

knotty sun
#

that is what passes for 'learning' nowadays. No actually brain or thought required

heady iris
#

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

knotty sun
#

yeah, no 'quick fix', no audience

heady iris
#

on the other hand, it would be significantly more useful for people who are actually interested in learning

inland lance
#

how do you make diffrent particle for a gun by hitting diffrent layers?

heady iris
#

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

leaden ice
#

And in your shooting code, grab this component from what you hit and call Hit on it

inland lance
#

ok thank you!

leaden ice
#

Another option is to use tags

sterile reef
#

Why do this on each surface?

leaden ice
heady iris
#

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

leaden ice
#

To be clear there are many different ways to do it

sterile reef
#

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

plucky inlet
#

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.

heady iris
#

It avoids tying your impact effects to other weird stuff.

leaden ice
# heady iris I like this idea the most.

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

heady iris
#

I'm not a fan of using layers, because that means you're eating up a lot of layers just for impact effects

leaden ice
#

oh certainly

heady iris
#

you want to use layers for conceptually different things

leaden solstice
#

Think you can do approach similar to "physics material"

#

Differnt sound, impact particle, etc

leaden ice
#

Yep exactly

heady iris
#

they just happened to fit together in most cases

leaden solstice
#

XY problem? ๐Ÿค”

heady iris
#

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

heady iris
#

and looking for the material on the object you hit would be problematic

#

you might have colliders on child objects that have no renderer

sterile reef
#

I mean.... with your component approach you can just make a script what pools the objects with the same scripts right?

leaden solstice
#

Usually: make designer assign correct one ๐Ÿ˜„

leaden solstice
#

Not my fault โ„ข๏ธ

heady iris
#

if you mean pooling the particle systems, then yeah

sterile reef
#

Yeah sadok

swift falcon
#

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

leaden ice
#

nothing to do with character movement systems

swift falcon
#

yeah I meant i want one without builtin animations, just the individual parts

leaden ice
#

You want one what

swift falcon
#

a person/humanoid

dusk apex
leaden ice
#

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

leaden ice
swift falcon
#

to make a custom movement system for fun

leaden ice
#

Is it because you can't figure out how to use a normal animated skinned mesh?

heady iris
#

this is ill-defined

swift falcon
#

sorry

leaden ice
#

Normally these are completely unrelated

#

or mostly unrelated at least.

heady iris
leaden ice
#

You can do that with a normal skinned mesh^

#

Just don't attach an animator to it.

heady iris
#

If so, this has nothing to do with rigging. You're just moving the armature with physics instead of an animator

swift falcon
#

ok thanks everyone ๐Ÿ™‚

heady iris
#

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

wary coyote
#

    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?
heady iris
#

yeah, if you use LookRotation where the direction and up-vector are identical, you won't get good rolls

wary coyote
#

What would you suggest in place of lookRotation? UnityChanThink

heady iris
#

I think you still want LookRotation, but with different inputs

wary coyote
#

I can do something other than it if for sure

heady iris
#

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?

wary coyote
#

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)

heady iris
#

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

wary coyote
#

        Vector3 tangentVector = torusRotation * new Vector3(-Mathf.Sin(innerAngle), Mathf.Cos(innerAngle), 0f);
        Vector3 direction = (outerRingPosition - finalPosition).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(direction, tangentVector);
wary coyote
heady iris
#

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

wary coyote
#

Looks good and works good (adjusting the torus diameters and circumferences)

heady iris
#

assuming that world-up is always your up works until it doesn't (:

wary coyote
#

Yeah ๐Ÿซ 

heady iris
#

actually getting that tangent can be a major problem for more complex situations

wary coyote
#

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 UnityChanThink positioning and rotationing is step 1, next is moving it

heady iris
#

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

wary coyote
#

Ooh okay yeah that makes sense. Ill refactor my direction codes out of the rotation method into standalones that can be called

heady iris
#

it's way easier to reason about problems when you're in the right space

wary coyote
#

torus-space

heady iris
# heady iris

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

wary coyote
#

actually this just made me remember:
A 2D map that loops NS and EW is a torus ๐Ÿค”

heady iris
#

the latter would be nice: [1,0,0] would be a normal vector when converted back into world space

#

If you have three vectors and an origin, you should be able to bash together a transform matrix..

#

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

wary coyote
#

Ill have to think deeply on this. I am good with logic but algebra, math transformations are my weak point

ionic tusk
#

How can I get the 2ยบ and 3ยบ class variables show on inspector?

heady iris
#

I don't see a TriggerColliderScript anywhere in the second screenshot

leaden ice
#

three of them actually

leaden ice
#

Each script needs its own file

#

and he one shown is not the one you attached to the object

ionic tusk
leaden ice
#

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

ionic tusk
leaden ice
#

You have a CS_Baliza attached to the object. The code in TriggerCollider1Script doesn't affect CS_Baliza

heady iris
#

you don't define more than one MonoBehaviour class per script file

leaden ice
leaden ice
#

what are you trying to do?

heady iris
#

and adding something to one class doesn't make it show up in another

leaden ice
#

THis is the wrong way to do whatever you're trying to do.

leaden ice
#

And when you write multiple scripts you have to put them in different files.

ionic tusk
#

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

ionic tusk
leaden ice
ionic tusk
leaden ice
stuck hollow
#

Can someone help me with this ?

ionic tusk
heady iris
#

did you read the error message

leaden ice
# stuck hollow

Look at the full stack trace of the error and go to the offending code and fix it

stuck hollow
#

i didn't touch any script i was doing my gui

heady iris
#

it explains the problem

knotty sun
heady iris
#

ah, see the stack trace then

ionic tusk
knotty sun
stuck hollow
ionic tusk
heady iris
#

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

leaden solstice
knotty sun
knotty sun
stuck hollow
gray mural
gray mural
#

And paste it here

knotty sun
#

it's the bit at the bottom of the console when you select an error

gray mural
#

The stack trace shows the full way to your error

stuck hollow
#

this ?

knotty sun
heady iris
#

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

stuck hollow
#

oh ok thx guys

#

it works now

stable lintel
#

can i add a disabled component to the object

#

or add and then disable, before component calls Start()

knotty sun
#

yes, although Awake will be called

late lion
stable lintel
stable lintel
heady iris
#

no, things run in an exact order

#

your code can't "delay"

deft pebble
#

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?

stable lintel
heady iris
stable lintel
heady iris
#

so you aren't actually having a problem

stable lintel
#

im testing a thing out rn

deft pebble
heady iris
#

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

stable lintel
#

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
heady iris
#

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

stable lintel
#

can i somehow prohibit object from updating unless jobhandle is complete

heady iris
#

I use raycast commands to batch up a bunch of work for my game's vision system

fallow quartz
#

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?

heady iris
stable lintel
#

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

heady iris
heady iris
stable lintel
#

the entire update in my case

heady iris
#

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)

stable lintel
#

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

fallow quartz
heady iris
#

checking handle.IsCompleted at the top of Update and returning early if you get a false is roughly equivalent to disabling the component

heady iris
#

it won't show up like that

stable lintel
heady iris
fallow quartz
#

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

somber nacelle
#

it's a LayerMask property, not a method

stable lintel
heady iris
#

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

stable lintel
#

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

fallow quartz
#

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

stable lintel
#

wdym you can't use inheritance

#

enemies and player are surely inheriting some kind of "LivingEntity" class/interface

heady iris
#

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

fallow quartz
#

So I make a class, instantiate inside the player and just take whatever I need?

fallow quartz
sterile reef
#

You can have multiple components on 1 object

#

And multiple of the same type

heady iris
#

here, have a look at one of my entities

void wedge
#

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?

heady iris
#

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

heady iris
sterile reef
#

Interfaces are a form of dependency injection

#

And I love using interfaces

sterile reef
heady iris
#

The icons are mine

#

I made them in blender!

sterile reef
#

Nice!!

... make them in blender?

#

I like the dedication

heady iris
#

i know it better than Illustrator lol

heady iris
#

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

sterile reef
#

Does the main entity subscribe to the components or do the components subscribe to the main entity

#

I got my answer

rigid island
somber nacelle
#

interfaces on their own are not a form of dependency injection, however many DI frameworks typically expect you to inject interfaces

rigid island
#

yeah that is true , most notably the asp.net one

sterile reef
#

Yeah true

#

Part of DI

rigid island
#

much cleaner with interface so you can switch up the implementations

sterile reef
#

I spread mischievous partial misinformation

rigid island
#

the "Brackys" route

sterile reef
#

Do you really need DI tho ?

somber nacelle
#

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

rigid island
#

you don't need to ever do "DI" or SOLID is just helps keeps stuff clean

somber nacelle
#

literally just passing an object to a method or an object ctor is DI

fallow quartz
#

And also, I cant figure out how to use forcesendlayers

heady iris
#

If you do this...

somber nacelle
heady iris
#
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

rigid island
heady iris
#

you can drag a Bar into it

heady iris
#

i injected 2 and 2 into the operator function

heady iris
#

these are both components

#

hence I am deriving from MonoBehaviour for both

fallow quartz
somber nacelle
#

=

heady iris
rigid island
sterile reef
#

I've used [serialized]

leaden solstice
sterile reef
#

And it works

heady iris
# sterile reef Both mono?

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

sterile reef
heady iris
#

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

fallow quartz
rigid island
fallow quartz
#

and you said i need to use the forcesendlayer for that

heady iris
#

are you even using 2D physics here

#

we should start with that

leaden solstice
rigid island
#

oh multiple. I mean 1 server app

heady iris
#

singleton't

fallow quartz
# heady iris are you even using 2D physics here

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

sterile reef
fallow quartz
leaden solstice
heady iris
#

it assigns the value on the right into the variable on the left

spring creek
fallow quartz
#

ok i think i got it

sterile reef
#

We should ask ourselves
Is playermask forcesendlayer

leaden solstice
rigid island
fallow quartz
#

so in that photo your making the layer of the object that has that collider apply to the layer of the playerLayer right?

heady iris
#

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

fallow quartz
#

so if i want to deny the collision forces between 2 dynamic objects to interact I cant?

heady iris
#

you can, but not by writing whatever that code is

#

You could give the player some extra time to get out of the boss's collider.

fallow quartz
#

like if it was a trigger but without it being a trigger

heady iris
#

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

sterile reef
#

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 atwhatcost

heady iris
#

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)

knotty sun
sterile reef
#

Oh wait yeah I forgot there were other channels ๐Ÿ’€

fallow quartz
#

because i never used that force layer thing

heady iris
heady iris
rancid frost
#

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

fallow quartz
heady iris
#

Are you asking about whether you need to configure the force layers on both the boss and the player colliders?

fallow quartz
#

So you need to go 1 by 1 declaring each layer?

heady iris
#

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

heady iris
fallow quartz
fallow quartz
#

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

heady iris
#

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

fallow quartz
heady iris
#

correct

fallow quartz
# heady iris 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?

heady iris
#

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

fallow quartz
bronze crystal
#

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.

vagrant blade
#

Because you never update the target position for the enemy. You've answered your question in your own second message.

fallow quartz
heady iris
#

that would be useless!

heady iris
fallow quartz
#

I dont want to push them

#

and i only added the receive boxCollider.forceReceiveLayers = layersForced; statement so i shouldnt be able to push them

heady iris
#

enemies can no longer push you away

#

therefore, you can overlap the enemy

#

therefore, you push them away

fallow quartz
fallow quartz
heady iris
#

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

fallow quartz
fallow quartz
latent latch
#

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

rancid frost
gray spruce
#

I used animation controller, and the player movement code is making the transitions possible

tawny elkBOT
fallow quartz
#

@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

gray spruce
# rigid island !code
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);
        }
    }
}
rigid island
rigid island
gray spruce
#

How can I animate a character that has gravity and a collider?

rigid island
#

with the same way you're doing it now ?

#

but just switch movement to rigidbody..

#

if you have to switch the animator

gray spruce
#

Thanks for the help!

gray mural
#

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

wide dock
#

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

heady iris
gray mural
leaden ice
#

Do they not?
I feel like I'm missing some context for this question

gray mural
#

This is its full version with just summaries removed

gray mural
heady iris
#

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

fallow obsidian
#

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");

heady iris
#

well, you capitalized it wrong

fallow obsidian
#

oh

#

brother

heady iris
#

i don't use Animation (it's an ancient component) but that's probably not helping

fallow obsidian
#

sorry i got boomer eyes haha

#

ah its a project that was already setup, trying not to change a lot of stuff.

fallow obsidian
snow lake
#

Hey my Unity editor isnโ€™t installing. Itโ€™s stuck on Editor Application please help.

tacit rover
#

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
heady iris
#

this is not a code problem

#

also, !install

tawny elkBOT
#
When Unity fails to install checklist
  • 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.
heady iris
#

adjust its sorting order so that it winds up in front

tacit rover
#

I've tried that but it doesn't seem like the scene manager is loading the 2nd scene, at all.

heady iris
#

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

tacit rover
#

Is that ScreenFader just another game object with a canvas component on it? Or is there other pieces to implementing it that way?

heady iris
#

Yeah, it's a canvas with a single Image on it

shell scarab
heady iris
#

The conditional expression split across a conditional compilation directive is...a little too clever, yes

#

(you can use #else)

shell scarab
#

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.

heady iris
#

right, I just wondered if that hid the error

shell scarab
#

perhaps. I skimmed the conversation after that code snippet and didn't see it mentioned anywhere so I thought it worth mentioning.

dapper schooner
#

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

leaden ice
#

could you explain that more

dapper schooner
#

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

leaden ice
#

Even if the camera is pitched or dutched

dapper schooner
#

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

leaden ice
#

of course you could. YOu could also just do it with a simple script

dapper schooner
#

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

rancid frost
void wedge
#

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
        }
    }
}
latent latch
#

I'd double check to make sure it's not just the UI displaying wrong first

leaden ice
#

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.

void wedge
#

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

leaden ice
#
   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
void wedge
#

yea I think thats the problem, im just getting the info from the hit on raycast then putting it in inv from that

leaden ice
#

ALso I think what you're calling an "Item" here would be better named as Stack or ItemStack

void wedge
#

so I need to check what im hitting, create a new instance of the item, then add it?

leaden ice
#

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

void wedge
#

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;
}

leaden ice
#

oh god it's a MonoBehaviour?

#

Why

void wedge
#

is it not supposed to be?

leaden ice
#

Make it a ScriptableObject

void wedge
#

ahhhhh I thought it really didnt matter so I went this route xD

leaden ice
#

It matters quite a lot

void wedge
#

yea I just attach it to the gameobject

leaden ice
#

it's like.. static data that defines the item

#

100% a use case for ScriptableObjects

void wedge
#

Then how would I link the gameobject with the scriptable object?

leaden ice
#

Reference it in the inspector

void wedge
#

Would I have a field to drag the prefab into the script so when I place the prefab it always is linked to it?

leaden ice
#

what prefab

void wedge
#

like right now I have a cube that I call "Gold" with the Item class attached to it

leaden ice
#

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

void wedge
#

Alright im going to learn how to do this so Ill get back to ya

latent latch
#

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

void wedge
#

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?

spring creek