#💻┃code-beginner

1 messages · Page 762 of 1

warm gull
#

my bad

#

wait no i dont understand

red igloo
#

I'm kind of confused cause I have this > transform.position = _portalRef.Exit.position; which already teleports the player to the exit portal so how would I teleport the player to the entrance portal when in the exit portal?

warm gull
#

i verified my trigger is what's not working, not the code. I will get back to you guys on whether or not the code works once i fix the trigger!

#

i appreciate all the help

languid pagoda
slender nymph
wintry quarry
#

Don't think of them in absolute terms. They are both exits and both entrances depending on where you start from

#

Each portal just considers itself the entrance and the other the exit

warm gull
#

Got it! My polygon successfully switches sprites upon colliding with the powerup. My mistake was having trigger checked but I was using onCOLLIDERenter2d. but now my powerup is solid and i bounce off of it.

If I re-tick trigger to make it not be a solid object and switch it to onTRIGGERenter2d, I get a green squiggly under OnTriggerEnter2D stating it has an incorrect signature

#

bam. fully working. thanks for the help guys

#

When I change sprites, I can hit "reset" on the Polygon Collider component for it to reset the bounds to the new sprites shape. Can I do that in the exact same function that changes the sprite in the first place?

wintry quarry
warm gull
#

i might call it here for today, im happy with my progress

umbral hound
#

Can anyone tell me why my gravity is fluctuating? It goes from gravity (0.025f) to 0f and back repeatedly

// Gravity
if (m_CharacterController.isGrounded)
{
    m_GravityPower = 0f;
    m_MoveDirection.y = 0f;
}
else
{
    if (m_UseGravity)
    {
        m_GravityPower -= m_Gravity;
    }
    m_MoveDirection.y = m_GravityPower;
}
#

For some reason the character controller is not grounded even when it is?

stable coral
#

I'm using a run of the mill third person cam script on a free look cinemachine, this is my movement script for the player. When I rotate the camera the player jerks back and forth and speed is adjusted when that happens. Here is the code for my movement ```private void MovePlayer()
{
movementDir = orientation.forward * verticalInput + orientation.right * horizontalInput;
rb.AddForce(movementDir.normalized * movementSpeed, ForceMode.Force);

    if (movementDir != Vector3.zero)
    {
        player.forward = Vector3.Slerp(player.forward, movementDir.normalized, Time.deltaTime * 5f);
    }
}```

I tried looking some stuff up but failed to find anything I understood. Could someone help me understand the way to do it?

#

From what I understand it's because the players rigidbody movement and position is directly affected by the camera's direction, which is what I want for the movement but the double edged sword is that it affects the position as well. which I'm not sure how to differentiate that. But if my understanding is misguided let me know.

wintry quarry
umbral hound
#

Just added a

CharacterController.Move(Vector3.up * -0.001f);
rocky canyon
fast relic
rocky canyon
#

couldn't think of how to do that..

#

since theres no Start() or Awake() that runs

#

maybe im just being stupid

sour fulcrum
#

there is awake and onenable but they are weird

rocky canyon
#

you mean they'll work when Creating via the project window?

fast relic
sour fulcrum
#

yeah they should

#

they also run ingame tho

fast relic
#

but also can't you just straight up give the fields default values? like

float myFloat = 15.0f;
rocky canyon
#

thank you bud!

#

didn't even see that

sour fulcrum
fast relic
#

yeah, fair

rocky canyon
rocky canyon
#

i like it

#

i've hesitated to use SO's for sooo long I actually forgot what little i knew about em 😆

#

i've just used simple Classes instead

sour fulcrum
#

SO’s are amazing

fast relic
#

they're really useful

#

it's nice having all data in the same place

rocky canyon
# fast relic they're really useful

i just finished up my SaveData system... now im working on the Menu.. and im thinking they could be useful to store
like the current settings data

#

and have it saved to the json file when game is exited or whatever (if they differ from defaults)

rocky canyon
sour fulcrum
rocky canyon
#

only.. so i think that may have subconciously made me neglect them

fast relic
rocky canyon
#

spit out my drink on that one

fast relic
#

i use them for channelling events sometimes haha

sour fulcrum
#

i tend to overuse SO's so im probably a little bias

rocky canyon
#

my last loading system had a SaveData class that i declared twice
once as the original (loaded into from the local save file)
and once as a run-time version..

and then i realized thats silly.. and i can use just (1) for both

sour fulcrum
#

public class ScriptableManifestManifest : ScriptableManifest<ScriptableManifest>
i love them

rocky canyon
#

but yea... i figured it was 💯 true about that non-changing data..

#

b/c u could always read from em and do w/e u need to do

sour fulcrum
#

can also make them at runtime but gotta handle it correctly

#

or as ways to handle selectable functions in editor in some contexts

timber tide
#

SOs make up for what little control you have over serialized classes

#

one day we'll get interface serialization out of the box with serialized references

sour fulcrum
#

eg. for a card game prototype i had a workflow where each ability a card had was a unique class inheriting from a scriptableobject, with 1 asset instance of that said class existing in the project so i could drag and drop it places. Then the functions on the scriptableobject run purely with the context being passed into them and static references so they don't need to store anything unique at runtime, eg.

public class Frontline : MoveData //MoveData is inheriting ScriptableObject
{
    public override IEnumerator OnActivate(MoveInfo moveInfo)
    {
        Debug.Log("Frontlining!");
        moveInfo.ally.player.MoveCardPosition(moveInfo.card, 0);
        RoundManager.RefreshCurrentStack();
        yield return new WaitForSeconds(1f);
        EndMove(moveInfo);
    }

    public override void Initialize(Card card)
    {
        Debug.Log("Initiliazing Frontline");
        card.onBeforeMove.AddListener(Activate);
        base.Initialize(card);
    }
}
rocky canyon
#

thats dope

cosmic dagger
cosmic dagger
rocky canyon
#

using Classes for data storage and knowing I could use a new() instance to set my defaults was a game-changer for me..
been sleeping on SOs for quite a while (well, i'll change that.. from today on I'll try to use SOs atleast once per prototype scene)

#

since im trying to fill out my exposure to things in Unity i've embarked on a journey of putting myself out there outside my comfort zones.. using the New Input System, utilizing SOs, next up UIToolkit.. and so on

#

ohh and events... 🤫, I mean i've used events.. but not like i ought to be using them.. and as frequently

cosmic dagger
rocky canyon
#

like this

#

i've never actually tried to use them anywhere else besides to load up default values for a script w/ lots of variables

cosmic dagger
#

Yeah, they're great for any kind of settings . . .

rocky canyon
#

ya, i guess the discussion is about whether u can or should rather, use em for runtime / or variables that'll change

#

and then having to read them prior

#

idk..

ivory bobcat
#

Like classes and other serialized types, it's great for exposing data to the inspector. The main difference compared to the other two would be where the data lives. With structs and classes, the data would likely be living on some component instance attached to a game object in the scene whereas with SOs the data would be attached to an SO instance (not associated with any specific scene object)

ivory bobcat
sour fulcrum
#

The more I can keep out of scenes the better and the more I can keep out of prefabs assets the better. (Imo)

Things that should just do things should not be reliant on knowing things in editor. ScriptableObjects are good at knowing things

#

Less points of failure

cosmic dagger
# rocky canyon like this

To use your first pic as an example; on a Jump component, you have an _action SO variable with a reference to an SO asset called Jump that has the variables needed to jump. If you get a powerup to double jump, you'd assign the SO asset called DoubleJump attached to the powerup to the _action variable. When you press the jump button, both SOs will display a different action because of their settings. This is easier than overriding many variables and doing so again to revert back . . .

#

As I mentioned before, I mainly use them for SO enums; much more versatility, because you can have fields and methods . . .

sour fulcrum
cosmic dagger
#

Oh, didn't know that . . .

sour fulcrum
#

eg. if a game handles some form of content via enum and an outside modder wants to expand that content

#

Another example of cool SO use that some people might find problematic is that if you have a reliable source of serialized information (eg. a singleton) you can use static getters to make information easily and globally accessible that is actually sourced from scriptableobjects that could be swapped out, eg. I often handle colors with something like

    static ColorLibrary _instance;
    public static ColorLibrary Instance
    {
        get
        {
            if (_instance == null)
                _instance = GlobalManager.Instance.colorLibrary;
            return _instance;
        }
    }

    public ColorWordsGroup damageColor;
    public ColorWordsGroup healthColor;
    public ColorWordsGroup currencyColor;

    public static Color Damage => Instance.damageColor.associatedColor;
    public static Color Health => Instance.healthColor.associatedColor;
    public static Color Currency => Instance.currencyColor.associatedColor;

This lets code access relevant coloring easily (via ColorLibrary.Damage etc.) but lets me control that colour from a single source

cosmic dagger
#

Yes, these are great for default/global settings . . .

#

I usually have a debug class with colors for info, warning, error, etc . . .

#

I use an SO for all of the UnityEngine.Time class fields, so I'm pulling them only once and using those values instead of calling into the engine inside of multiple components . . .

rocky canyon
# cosmic dagger To use your first pic as an example; on a `Jump` component, you have an `_actio...

ohhh... i feel like i might know why..
i dont think my projects have ever grown or matured enough for me use them enough
like now that i think about it, if the types of games i made were to be say.. a game w/ a big inventory or a game w/ a big skill tree or even a more simple game like mine, a shooter, had more powerups or weapon combinations or variations i feel like i'd use them out of design choice.. orr if my game was just getting really big.. or i was working on something like an rpg or some complicated ui/ux gameplay system i might be forced to use them more out of necessity

ivory bobcat
# rocky canyon idk..

So imo:
-Managers for data that should persist between scenes (and possibly the entirety of the applications life)
-Scriptable Objects for non mutable data that should persist between scenes (and Editor play sessions)

rocky canyon
#

i might just need to use em just to practice.. or expand faster 😄

rocky canyon
#

i just like the monobehaviour being attachd i guess 😊

#

but thats still not an excuse

rocky canyon
#

i just haven't really gotten to there yet.. most of my data lives in their own sub-system classes

#

and all hardcoded i guess u could say

#

ahhh.. eureka moment lol

willow iron
#

what would be the best way to detect a click on a 2d sprite from camera that will be moving?

rocky canyon
#

figured it out.. my game isnt classy enough

ivory bobcat
rocky canyon
#

if it were ui or something i'd say the IPointer interfaces

#

or i guess it can work there too.. idk never used it on sprites

fast relic
spiral summit
#

I need your help

rocky canyon
#

didn't know it was specific to 2d tho

#

thought it was just a PhysicsRaycaster

frosty hound
rocky canyon
#

click anything in the scene and press F

fast relic
#

since 2d and 3d physics are pretty much completely different systems

rocky canyon
#

the more you know..

#

i know they're diff systems but i just had thought they shared the same component for Raycasting.. that doesn't make too much sense when i say it out loud

cosmic dagger
fast relic
#

i feel called out because an empty scene with cubes (well, squares even) and components is exactly what i have rn

cosmic dagger
#

When I see what other people have, like Spawn's triangle shooter, that's when I flood with a bunch of ideas that I could implement . . .

sour fulcrum
#

prototyping my beloved

#

i have so many abandoned ideas

#

so hard to commit to things and push past getting stuff actually going

#

eg. i spent a day or two messing with an idea where you'd do some kinda town/city building thing as a way to teach basic computer networking but i got stuck on something and into the pit it goes

rocky canyon
#

i've actually adopted that work-flow for alot of systems.. they "theorhetically work" b/c the values are there.. but nothing to represent them just as yet 😄

cosmic dagger
cosmic dagger
cosmic dagger
rocky canyon
#

soo far this is like the optimo setup for me.. been much more organized and therfor productive by having 2 different projects one being more "back-end" unseen stuff
and the other being the visual and physics gamestuff

chrome apex
#

If I want a camera to follow a rigidbody, it's best to follow it with code in late update, rather than something like parenting it, correct?

grand snow
limber turtle
#

i haven't gotten anything done in the past 4 weeks because i've been going back and forth on this one issue and now i'm just going to give up and find an easier solution. is it possible to use aron granberg's a* solution in tandem with custom movement programming? the enemy i am trying to make is hopefully going to move around the player and shoot at them instead of just moving directly towards them

slender nymph
#

yes, that's what it was designed for. you use the pathfinding to just generate the path, then use that path literally however you want

limber turtle
#

oh

#

so if my enemy has line of sight with the player i can make it ignore the pathfinding and just start moving in its own way

tepid remnant
#

Is there an easy way to implement a timer that resets a variable after it has elapsed? I have an int that I having change on player input, then return to the original value after half a second has passed. If the player presses a button in that half second, the timer should restart

slender nymph
limber turtle
#

alright

tepid remnant
limber turtle
#

i guess i'm going back to aron granberg's then

slender nymph
#

remember, you don't have to set the target destination for a path to the player's position. you can use whatever valid position you'd like.

limber turtle
#

what do i do about this

slender nymph
#

well the last warning actually provides a suggestion for what you can do about it, and presumably the error is related

limber turtle
#

i don't know what webplayer or standalone is

#

do i just have to change the build settings?

slender nymph
#

what is your current build target

limber turtle
#

where do i find that

#

i have never made a build before so all i know about build settings is that you can use it with scene management

slender nymph
#

presumably you have selected "Web" as your build target . . . in the build settings.

limber turtle
#

i'm definitely being stupid and/or blind right now

#

i can find a build profiles window but not build settings

slender nymph
#

it's that

limber turtle
slender nymph
#

well there you go, you have windows selected, not web

limber turtle
#

the message said it wouldn't work with web

slender nymph
#

i never said to switch to web. i am simply pointing out that isn't the issue.

limber turtle
#

right yeah

#

what else could it be

wanton osprey
#

Is there any way i can integrate c++ into unity?

slender nymph
#

not directly, no. you can use c++ to write native plugins that your c# code can then access

#

if you want to use c++ why not choose an engine that actually supports it directly, like unreal?

wanton osprey
#

so theres no way to code a unity game in c++

hexed terrace
#

there is no point even trying

wanton osprey
slender nymph
#

then make your art style different?

#

you do know that the engine doesn't dictate your art style, right?

wanton osprey
#

i want something like unitys

#

and unreal just confuses me

slender nymph
#

then learn c#

wanton osprey
#

im trying but i also want to learn c++

slender nymph
#

but if unreal is confusing you, then unity will too

hexed terrace
#

you either learn Unreal lighting or learn C# for Unity..

wanton osprey
placid jewel
#

C# is fairly similar to C++ relatively speaking, so you might as well learn C#

placid jewel
wanton osprey
#

with c#

placid jewel
#

Then keep using it?

wanton osprey
placid jewel
#

You can do that too

slender nymph
wanton osprey
#

i will try

placid jewel
#

No one is stopping you from knowing multiple languages, in fact for overall developer skills it's probably a good idea

placid jewel
#

Ok

wanton osprey
#

i want to keep using unity but also want to learn c++

placid jewel
#

Then learn C++ seperately to Unity and learn C# with respect to Unity

wanton osprey
#

ok

placid jewel
#

I don't see how it's a problem

wanton osprey
#

ok im done trying

placid jewel
#

Damn

wanton osprey
#

im just gonna learn c# then c++

placid jewel
wanton osprey
#

alright

#

thanks

tender mirage
#

basically this script gets the scriptable object assigned to the tile below and the above script is what i don't get. i'm lost at the process of dictionaries

hexed terrace
#

for long code blocks like that, don't paste in chat - use a paste site

#

!code

radiant voidBOT
tender mirage
hexed terrace
#

Dictionaries have <key, value> ... TileBase is your key. You pass in the key and get out the value (TileData)

tender mirage
hexed terrace
#

When you add data to the Dictionary, you give it a key and value

limber turtle
#

the red squares are the obstacles, right? i don't know what happened with the scan but i think something went wrong

#

i'm just going through a tutorial right now and idk what caused this

tender mirage
hexed terrace
#

I dunno if Dictionaries are classed as tables or not

tender mirage
#

i was still thinking they might've been tables.

#

understanding what it is, is what's throwing me off. i was trying to add more then 2 arguments inside of a dictionary

#

which didn't go so well.

limber turtle
#

i disabled this and now everything is blue

limber turtle
#

it thinks that the whole area is unwalkable

rich adder
#

oh alright. been a while since i used the A* pathfinding project

limber turtle
#

i disabled that but now everything's blue, including the area i don't want to be traversable

slender nymph
#

this isn't a code issue

limber turtle
#

where do i take this then

#

where do i go for help with this

hexed terrace
languid pagoda
#

So my game will be on steam but am also releasing it for sale on my website, I need a clean way to differentiate which version of the game the player is running.

I thought about either using #if STEAM and calling it a day but there are some problems with that. It messes up serialization, for example if you wrap a variable in an #if and assign it from the inspector then the condition of that isn''t met the variable resets to default value the next time it is met. Additionally I would have to build the game twice per platform each update.

I also thought about using launchParameters from steam and just having if() wrapping the calls but that is messy. Any other ideas?

broken hull
#
using System.Runtime.CompilerServices;
using UnityEngine;

public class PlayerAnimation : MonoBehaviour
{
    private Animator myAnimator;
    private const string IS_WALKING = "IsWalking";
    [SerializeField] private Player player;
    private void Awake()
    {
    

    myAnimator = GetComponent<Animator>();
        myAnimator.SetBool(IS_WALKING, player.ISWalking());
    }
}

#

using System.Runtime.CompilerServices;
using UnityEngine;


public class Player : MonoBehaviour

{

    [SerializeField] float moveSpeed = 7f;
    [SerializeField] float rotateSpeed = 10f;
    private bool isWalking;
    private void Update()
    {
        Vector2 inputVector = new Vector2(0, 0);

        if (Input.GetKey(KeyCode.W)) inputVector.y += 1;
        if (Input.GetKey(KeyCode.D)) inputVector.x += 1;
        if (Input.GetKey(KeyCode.S)) inputVector.y += -1;
        if (Input.GetKey(KeyCode.A)) inputVector.x += -1;

        inputVector = inputVector.normalized;
        Vector3 moveDir = new Vector3(inputVector.x, 0, inputVector.y);
        transform.position += moveDir * moveSpeed * Time.deltaTime;
        isWalking = moveDir != Vector3.zero;
        transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
    }
   public bool ISWalking() { 
        return isWalking; }
}
#

I’d really appreciate it if someone could help me find the error in this animation

#

the transitions between animation is not working

glossy cosmos
slender nymph
#

what object is that component attached to

wintry quarry
#

You should also explain what you are trying to accomplish

#

Note that this code is almost certainly wrong:

glossy cosmos
wintry quarry
#

0 * 10f * Time.deltaTime is just going to be 0

#

So effectively all this code will do is move the object UP by one unit

#

from the 1 you have

glossy cosmos
wintry quarry
#

And since the object is not the camera and it's just an empty object, it doesn't really matter if you move it

wintry quarry
#

what's actually going wrong here?

wintry quarry
slender nymph
#

i'm betting this is also a 6.1+ issue and they are just ignoring the console

glossy cosmos
wintry quarry
#

Drag the game view window side by side with the scene view so you can see them both

#

and you don't have to rely on the camera preview thing

glossy cosmos
#

but when I didn't use Input.KeyUp the camera worked well

slender nymph
#

look at the console

glossy cosmos
#

a.. ok

broken hull
glossy cosmos
#

there is

slender nymph
slender nymph
radiant voidBOT
# slender nymph !input 👇
How to Set Input

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.

glossy cosmos
#

thx

slender nymph
#

for future reference, don't ignore the console. it's typically best to have it visible while playing, and for extra points Error Pause is useful since it will pause execution on any error

broken hull
#

that would execute eveery frame

old remnant
#

Hey, I am a bit new and I need some advice regarding the input and animation change.

I've connected the animation as it should and I thought I'd want to try out something new with the bool values to change my animation.

This is what I've currently got scripted, but doesnt work, anyone see the issue?

    public Rigidbody2D rb;
    public float moveSpeed = 5f;
    private Vector2 _moveDirection;
    public InputActionReference move;
    public Animator animator;


    private void Start()
    {

        animator = GetComponent<Animator>();

    }




    // Update is called once per frame
    void Update()
    {
        _moveDirection = move.action.ReadValue<Vector2>();


        if (_moveDirection.magnitude > 0.1f)
        {
            animator.SetBool("IsMoving", true);
        }
        else
        {
            animator.SetBool("IsMoving", false);
        }
    }

    private void FixedUpdate()
    {
        rb.MovePosition(rb.position + _moveDirection * moveSpeed * Time.fixedDeltaTime);
    }
#

I did have
if (_moveDirection != Vector2.zero)
before but it didnt work either

wintry quarry
#

"doesn't work" is a bit too vague

willow iron
#

does anyone know have a tutorial for the physics2Draycaster? im trying to find information on it, but all of the tutorials im finding regards 2d raycast instead of physics2DRaycaster, and the documentation isn't very specific. trying to make a script that detects clicks on 2d sprites with colliders on them but cant figure it out

wintry quarry
#

if you want to perform your own 2D raycasts you'd use Physics2D.Raycast and other related functions in your own code

wintry quarry
#

if you want to detect clikcs on 2d objects yes you can and should use Physics2DRaycaster and the event system

#

What issues are you having with it specifically?

#

Do you have:

  • An Event System in the scene
  • A Physics2DRaycaster on your camera?
  • A Collider2D on the sprite object?
  • The appropriate code in your script attached to the object with the collider?
willow iron
old remnant
scarlet pasture
#

i know that this Script is a little bit so bad, i did one enemy Ai and now im working on it, it is a little bit hard to make a boss, but i learned that i need to start a little bit slower atwhatcost sadok

wintry quarry
#

"debugging" is just the act of investigating and solving bugs

wintry quarry
scarlet pasture
#

i want that he only shoots, and not running, but he runns and shoots at the same time

scarlet pasture
#

yeah

wintry quarry
#

I don't see anything in here that would prevent walking and spitting at once

#

I see basically two disjoint state machines in here

#

one for movement, one for attacking

#

Can you point to the code that is intended to prevent shooting while moving?

#

I think what you need to do here is merge your two state machines into one

#

spitting and moving should be separate, mutually exclusive states

edgy sinew
#

ich laufe kekwait ur german bro?

#

You can also just update a bool variable accordingly ... bool canShoot
If you wanted to keep the 2 disjoint/independent state machines setup

old remnant
#

the idle works fine ofc but it just doesn't wanna transition into walk when I am making a input (move around)

#

the only thing I think might be the problem is this though
(_moveDirection is the vector2 values)

wintry quarry
#

You should be able to see right there if it's being set properly

scarlet pasture
wintry quarry
#

Also that code can be simplified without if/else: cs animator.SetBool("IsMoving", _moveDirection != Vector2.zero);

old remnant
old remnant
wintry quarry
# scarlet pasture what do u mean

you said:

i want that he only shoots, and not running, but he runns and shoots at the same time
But I don't see any code that seems intended to cause that behavior. If it exists, point to it. If it doesn't exist, then that is the cause of your problem.

old remnant
#

my animator parameter had a lowercase i but uppercase on the script hahsa

#

thank you for your help though!

scarlet pasture
grand snow
#

oof but now you know for the future that its case sensitive!

scarlet pasture
#

i mean this should prevent that the Frog dont jump ands shoot at the same time

wintry quarry
# scarlet pasture

that will prevent you from spitting if you're already spitting.
It won't prevent you from spitting if you're walking or jumping or whatever

old remnant
scarlet pasture
grave frost
#

am I using this contact filter wrong?? Why is it getting things that aren't on the provided layer? It keeps listing the spawn area pictured in the third image as one of the first things in the buffer. The first image is the script this code is from, showing the inspector.

private void FixedUpdate()
{
  var mousePos = _mousePosition.action.ReadValue<Vector2>();
  Vector2 worldPoint = _camera.ScreenToWorldPoint(mousePos);
  var hit = Physics2D.OverlapCircle(worldPoint, _radius, _filter, _colliderBuffer);
  for (var i = 0; i < hit; i++)
    Debug.Log(_colliderBuffer[i].gameObject.name);
}
[SerializeField] private LayerMask _layerMask = 1 << 8;
private ContactFilter2D _filter;

private void Awake()
{
  _camera = Camera.main;
  _colliderBuffer = new Collider2D[_bufferSize];

  _filter = new ContactFilter2D
  {
    layerMask = _layerMask
  };
}
wintry quarry
#
_filter = new();
_filter.SetLayerMask(_layerMask);``` this will do it properly
#

or:

  _filter = new ContactFilter2D
  {
    layerMask = _layerMask
    useLayerMask = true
  };
}```
#

I would recommend just exposing the contact filter directly in the inspector though

grave frost
#

oh i didnt even think of that

wintry quarry
#

instaed of:

[SerializeField] private LayerMask _layerMask = 1 << 8;
private ContactFilter2D _filter;```
And using code in Awake. You should just do:
```cs
[SerializeField] private ContactFilter2D _filter;```
grave frost
#

I ended up doing

[SerializeField] private ContactFilter2D _filter = new()
        {
            layerMask = 1 << 8,
            useLayerMask = true
        };

because it said I couldnt convert from int to ContactFilter2D.

wintry quarry
#

correct, because it's not an int, it's a ContactFilter2D

#

Sorry I adjusted the example above

#

you don't need to set any default

#

but if you do want to set a default you can do it as you showed

scarlet pasture
#

how can i shoot somthing in the right directionn, like if the Enemy Shoots left the bullet also should go left? how can i detect the righ5t direction and how do i code that?

#

because i used a method the looks if the local scale.x is 1 shoot in that direction and the same code logic for the other, but i have the feelinng that this is not the normale way to do that.

wintry quarry
scarlet pasture
#

thanks!

cerulean bear
#

I'm getting a null reference exception on this

Startingtransform.position = gameObject.GetComponent<Transform>().position;
Startingtransform.rotation = gameObject.GetComponent<Transform>().rotation;
slender nymph
#

Startingtransform is null

#

also you never have to use GetComponent to get an object's transform, every gameObject and component has a transform property that already references it

wintry quarry
#

save yourself typing^

cerulean bear
#

oh ty

stable coral
#

does anyone here use cinemachine alot or have good experience with third person game creation

stable coral
wintry quarry
grand snow
#

"hello may i ask question about thing" ❌
"hello i have error x and i tried y" ✅

stable coral
#

Ah I understand. I asked earlier but I don't think anyone was available at the time.

#

Then again that was yesterday.

slow fossil
#

Hello, java developer here,
Is it also possible to create instances of an abstract class with objects? Basically I'm trying to make a tower defence game from scratch and wondered what would be a good architecture

grand snow
#

abstract classes cannot have instances made but ofc if you inherit from that then thats fine

slow fossil
#

oki thanks

grand snow
#

the point of abstract is to have abstract methods and properties which then must be implemented

scarlet pasture
#

does somone know why the Spit is not flying? better said moving?

wintry quarry
#

Unity is made for composition

timber tide
#

you can declare by the abstract type assuming you do insert a more derived type in the editor, but new-ing an abstract class is ano

slow fossil
wintry quarry
wintry quarry
scarlet pasture
wintry quarry
#

like Tower would have things common to all towers - the size, the collider, the cost, the experience curve, etc.
ArcherBehavior would actually "do" the archer tower stuff

scarlet pasture
#

but yess i will try it give me one second

#

u was right

#

now Rigidbody

#

but why?

#

can i say give the Object a Component? instead of saying get a Component?

grand snow
#

you can add components with code yes

scarlet pasture
#

i will add it via editor for performance but i also want to know how to give one

#

can u teach me how?

scarlet pasture
#

Thanks

grand snow
#

you are right to realise that its better to just add the component before hand in editor

scarlet pasture
slow fossil
scarlet pasture
wintry quarry
slow fossil
slender nymph
grand snow
#

^ yea that

wintry quarry
scarlet pasture
#

okay thanks!!

wintry quarry
#

And what do the arrows represent?

#

GameObjects?

#

Components?

#

Classes?

slender nymph
slow fossil
#

classes are boxes
arrows represent the inheritance and in this case also the composition

wintry quarry
#

There wouldn't be an Archer class

#

there would be a GameObject named Archer or "Archer Tower" with two components attached to it - Tower and ArcherBehavior

#

(and probably others too but we're just focused on these)

slow fossil
#

I see

timber tide
# slow fossil So something like this? Where the tower base and the archer behavior defining wh...

My way of doing this is have that single Tower class as the controller. This class would have basic information as Radius, Rotation to attack, and cost to build. Now, for the mode to attack I would accept some sort of ShotData class data that when radius and rotation is satisfied I would Shoot(ShotData shot, position, direction).

Some things to think about when doing this controller + projectile class is that you've two parts, the controller to spawn the objects, and the behaviour of the projectile itself.

wintry quarry
#

It kinda depends how much variance there actually will be in the tower behavior, and how much of it you can shove down into the projectile prefab for example

timber tide
#

The projectile itself doesn't need information about how many projectiles are spawned, only how it moves. So this data to say make a fan like shape of projectiles must be presented before that

slow fossil
#

Isn't it laggy to create lots of projectiles?
I just thought of doing a Attack() function that gets called when there's an enemy in range to not have any sort of delay

timber tide
#

Ignore optimization and deal with it later if you need it

slow fossil
#

I don't understand the shotdata part

#

the tower class would have an enum with all possible projectiles?

timber tide
#

Ok how about this. You have three types of data that define how this projectile(s) is instantiated, and data for how that projectile moves. First data component would define targeting like radius, firing like attack speed, and build costs. Second data type would provide how many projectiles are spawned and in what pattern as an example. Third data type would be how this projectile moves such as homing and perhaps variables like gravity.

#

Heck, can do a 4th data type for Hit data for when that projectile collides

#

TowerData, FiringSessionData, ProjectileData, HitData

#

Tower -> main driver
FiringSession -> Temporary class needed to a coroutine execution of a sequence of projectiles or anything a bit more complex you don't want to do inside of the towercontroller
Projectile -> projectile driver
HitData -> Only exists in data really so no instantiated really needed... similarly FiringSession could just be data too but if you want to run any sort of coroutine it needs to be on the scene instantiated

slow fossil
#

How to have an enemy detection range?
My goal : When an object type Enemy enters the range of my tower, it attacks
I'm looking at Enemy[] enemies = FindObjectsOfType<Enemy>(); but it is said to be deceprated

#

How can I detect an object when it enters a range x?

wintry quarry
wintry quarry
slow fossil
polar dust
#

A depends on B

marsh vale
#

hey hey can anyone help me out here? i have no idea how to turn this off

fast relic
#

you can either use the new input system (the recommended way) or change your player settings

marsh vale
#

yeah i want to know how to switch it off for just this practice project

slender nymph
#

!input

radiant voidBOT
# slender nymph !input
How to Set Input

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.

marsh vale
#

ill definitly use the new one since ive heard great things but I need to learn the unt y fundermantals first

#

tyty

fast relic
marsh vale
#

i will be learning that next then

#

but im just following this video, its just introducing some very basic things

#

pong game

#

and its using unitys old movement system

fast relic
#

you should still try to do something yourself, try to modify it - just following it blindly won't teach you much

marsh vale
#

ill be completing this tutorial then im going to make a new project with one cube, and try adding basic controls to it using the new system.

#

thats my plan

fast relic
#

i'm not really a fan of "completing" or following tutorials in general - i feel like trying to adapt the tutorial or expand on it somehow will teach you a lot more than just following it

#

but hey, you do you

#

maybe you can try learning about the input system, then coming back to the pong game and making it use the new input system

marsh vale
#

good idea,

#

i shall do that

old remnant
#

Anyone can see why my char can flip when I move to the left?

fast relic
#

Flip() is never called

#

your ide is even darkening the name

#

because it's not used

old remnant
#

it's always the small things haha

#

thanks for pointing it out

paper peak
#

VS studio says .velocity is obsolete for rigidbody, is this true for any kind of project?

#

Atm im working on a 3D game with 2D view

slender nymph
#

yes. it should also be telling you what to use instead

paper peak
#

Yeah it tells me to use linearVelocity instead

#

But github copilot really insists that linearVelocity doesnt exist

slender nymph
#

don't trust AI, trust the compiler

paper peak
#

Just wanted to make sure i wasnt going crazy

#

Thanks

teal viper
polar dust
#

its nice of the Unity team to make changes to their API to mess up the spambots output

teal viper
#

I don't think that was the purpose...

#

To be fair, that change was as surprising to humans as it is to AI.

polar dust
#

yeah, I'm only kidding 😅

#

it's funny to ask gpt about the property and it INSISTS .velocty is correct despite telling it otherwise

It's a very strange invention

tawdry valley
#

Hi, i am trying to build a 3d rigidbody character controller and i am facing a problem. When i jump my character constrantly goes up and gravity doesn't show any effect. What could be problem?

private void Jump()
    {
        if (!_isGrounded)
            return;
        _isGrounded = false;

        rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    }
ionic orchid
frigid sequoia
#

Is there not a way to get a more direct access to the values of an audio mixer than to search it with a string??

tawdry valley
# wintry quarry Show your full script
using System;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private Rigidbody rb;
    [SerializeField] private Transform body;

    [SerializeField] private float moveSpeed = 5f;
    [SerializeField] private float jumpForce = 7f;
    [SerializeField] private float groundCheckDistance = 7f;
    [SerializeField] private LayerMask groundLayer;

    private Vector2 _moveInput;
    private bool _isGrounded;

    private void OnEnable() {
        InputManager.Instance.OnJumpPressed += Jump;
    }

    private void Awake()
    {
        rb.freezeRotation = true;
    }

    private void Update()
    {
        _moveInput = InputManager.Instance.GetMoveInput().normalized;

        CheckGround();
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void Move()
    {
        Vector3 direction = (body.forward * _moveInput.y) + (body.right * _moveInput.x);
        Vector3 targetVelocity = moveSpeed * Time.fixedDeltaTime * direction;
        Vector3 velocityChange = targetVelocity - rb.linearVelocity;
        velocityChange.y = rb.linearVelocity.y;

        rb.AddForce(velocityChange, ForceMode.VelocityChange);
    }

    private void Jump()
    {
        if (!_isGrounded)
            return;
        _isGrounded = false;

        rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    }

    private void CheckGround()
    {
        _isGrounded = Physics.Raycast(body.position, Vector3.down, groundCheckDistance, groundLayer);

        Debug.DrawRay(transform.position, Vector3.down * groundCheckDistance, _isGrounded ? Color.green : Color.red);
    }
}
frigid sequoia
#

Add a debugLog on the "_isGrounded" check on jump

tawdry valley
#

i checked my jump method trigger once then i hit space

frigid sequoia
#

Well, if you set the y velocity to zero, of course the gravity is not gonna do anything

tawdry valley
#

i also removed that line and tried again 🙁

#

is that could be a unity bug or something?

fast relic
wintry quarry
frigid sequoia
#

Yeah, aren't you reseting the Y velocity each frame on the move part?

tawdry valley
frigid sequoia
#

But still should not be gaining heigh infinitely right?

fast relic
#

it's just a simple acceleration

wintry quarry
#

Velocity change mode itself was not the problem, but would certainly amplify it

#

You still have the issue

#

It's the second to last line in your move() function

#

Delete that

#

It looks like it was left over from some earlier movement code

tawdry valley
#

so should i directly give direction?

wintry quarry
#

I didn't say that no

tawdry valley
#

but didn't i overrride Y when i move?

fast relic
#

so you're literally taking the y velocity and adding it (per second) to the velocity

frigid sequoia
#

Your move method should prob not be doing anything to the y velocity anyways

tawdry valley
#

ok i get it now

#

thanks 🙏

fast relic
#

-# also you should normalize your move direction

tawdry valley
#

i do that

fast relic
#

oh yeah right, missed it

drifting cosmos
#

when I start the game and my mouse is off the game tab like in scene view it gives me an error but if i have it on the game tab then swap to scene it still works im tracking the mouse every frame im not sure if this is a problem or if its just an editor thing

drifting cosmos
# fast relic what's the error?

Screen position out of view frustum (screen pos inf, -inf, 0.000000) (Camera rect 0 0 1920 1080)
UnityEngine.Camera:ScreenToWorldPoint (UnityEngine.Vector3)
MeleeRangeController:FollowMouse () (at Assets/Scripts/MeleeRangeController.cs:43)
MeleeRangeController:Update () (at Assets/Scripts/MeleeRangeController.cs:36)

fast relic
#

inf, -inf is interesting

winged ridge
drifting cosmos
ionic orchid
willow iron
#

hello! trying to use cinemachine, but it seems that cinemachine no longer uses priority to switch cameras? priority is now a checkmark that is set to default off. If priority is no longer the main way of changing virtual cameras, then how do transitions using code work?

cloud moss
#

For reasons I cannot ascertain, Visual Studio is not interfacing with its tools for Unity plugin. I’ve made sure I actually have it installed (quintuple-checked, at this point), I’ve made sure Unity has its own Visual Studio plugin installed, and I’ve made sure Visual Studio is set as the external editor in Unity. I’ve tried uninstalling then reinstalling both Visual Studio and the Unity tools plugin for it, I’ve tried restarting the programs themselves and my entire PC, and it just isn’t doing anything beyond what non-Unity Visual Studio would do. Visual Studio is 2022 (17.14.19), Unity is 6000.0.26f1.

#

Update: deleted the vs-related files in the root folder and regenerated the project files, that did the trick

#

Not sure why jumping through hoops to fix this was necessary but it's been fixed nonetheless

teal viper
#

There's the "regenerate project files" button in external tools that usually fixes such issues.

glossy cosmos
#

what should I do?

#

I do it, don't pay attention

gaunt raptor
#

can someone help me to import 3D model from blender into unity, i've add the fbx using import new assets to the project but the material and texture in blender doesnt work in unity. if you know some youtube tutorial or documentation that you can share to me or even better guide me via share screen i will appricate it. Thank youu

keen dew
#

also not a code question

gaunt raptor
keen dew
gaunt raptor
#

okay thankyou

scarlet pasture
#

hey does somone know why this code better said debug.log never gets shoot

#

i mean i used it correctly and i dont see a problem?

timber tide
#

did you mean to say it never executed the line where debug.log is at?

#

because waiting for callbacks from the animator may never happen

scarlet pasture
#

yeah i want to know why my debug.line never gets runned

scarlet pasture
timber tide
#

personally I wouldn't yield against the animator. You should have your own statemachine that is calling the animator, you shouldn't need to rely on the animator to tell you the state

#

but if you do want extra logic to execute when an animation does play, I would suggest using animation events and injecting directly into the timeline

scarlet pasture
timber tide
#

Ah, yeah I see. Maybe duplicating the animations with different events but that does seem annoying. Could potentially modifiy a single clip at runtime and swap out what that event does.

#

but at that point you might as well just call the method if it's supposed to execute at frame 1

compact sandal
#

I added a flamethrower and enemies to burn, but now want a fire particle to appear when i actually burn them. Where do i start with this?

fast relic
lyric grail
#

is it normal that errors dont get shown in like a res underlining in visual studio?

hot wadi
#

There are all kinds of error. What issue are u facing?

radiant voidBOT
hot cliff
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 1f;

    private PlayerControls playerControls;
    private Vector2 movement;
    private Rigidbody2D rb;
    private Animator myAnimator;
    private SpriteRenderer mySpriteRender;


    private void Awake() {
        playerControls = new PlayerControls();
        rb = GetComponent<Rigidbody2D>();
        myAnimator = GetComponent<Animator>();
        mySpriteRender = GetComponent<SpriteRenderer>();
    }

    private void OnEnable() {
        playerControls.Enable();
    }

    private void Update() {
        PlayerInput();
    }

    private void FixedUpdate() {
        AdjustPlayerFacingDirection();
        Move();
    }

    private void PlayerInput() {
        movement = playerControls.Movement.Move.ReadValue<Vector2>();

        myAnimator.SetFloat("moveX", movement.x);
        myAnimator.SetFloat("moveY", movement.y);
    }

    private void Move() {
        rb.MovePosition(rb.position + movement * (moveSpeed * Time.fixedDeltaTime));
    }

    private void AdjustPlayerFacingDirection() {
        Vector3 mousePos = Input.mousePosition;
        Vector3 playerScreenPoint = Camera.main.WorldToScreenPoint(transform.position);

        if (mousePos.x < playerScreenPoint.x) {
            mySpriteRender.flipX = true;
        } else {
            mySpriteRender.flipX = false;
        }
    }
}

was following a tutorial on youtube but then i got this error. how do i fix this? its basically a movement script for my sprite

wintry quarry
#

In the tutorial they named it PlayerControls

#

You named yours something else

hot cliff
wintry quarry
#

Also make sure your movement speed variable is set to something reasonable in the inspector

ivory bobcat
#

This is the beginner coding channel. If it's not related to coding and you're unsure where to ask, try #💻┃unity-talk

distant robin
#

great

coral patio
#

Hey knowledgeable people, is it possible to get persistent unique ids for game objects by default? Reason: we have about 3000 collectables and are working on a save system so we need to be able to spawn or despawn them in. Or is there an particular better way I am missing?

Our idea was to write in arras of object with some BSON and other data as a save file

inland apex
#

When the joined player jumps , in the host's screen the joined player jumps and eveything works fastly . But in joined player screen its slow ( not so much ) . Does anyone know what is the problem ?

slender nymph
#

!code also 👇

radiant voidBOT
scarlet pasture
#

hey, i want that the frog should play a "Hurt" Aimation if he gets Attacked by the Player, but i have the feeling that if the Player Attacks the Frog boss to much he will be in a Hurt Loop, i thought about this Game Design. If the Boss is currently dont Attacking he is allowed to play the Hurt Animation, but if he is Currently Attacking i wil not allow to play the Hurt Animation, only allowiungt o blink white for a short time, how can i code that.

cosmic quail
scarlet pasture
#

i need to this guard on every state?

cosmic quail
slow fossil
#

Should I choose layer or tags ?
I basically want to create a way to differentiate enemies from anything

sour fulcrum
hot wadi
sour fulcrum
#

Personally I don't know of any reason why you would use tags over component checking period

#

layers are good for avoiding broad groups of interactions though yeah

keen dew
#

Tags are fine for broad things that don't have any other functionality than checking what it is. For example for ground checks, much cleaner to just set a ground tag instead of making an empty component and attaching it to every ground element

hot wadi
#

I use physics cast to check ground and layer is required

keen dew
#

but yeah if you're going to need the component anyway there's no point in first checking for an enemy tag and then doing getcomponent on it

sour fulcrum
tender onyx
#

Hey y'all, I'm wanting to add colored outlines to drops in my games so the player can tell it's level easier. I have an outline material and URP setup, but I can't seem to change it's color. Multiple materials seem to break the renderer, only rendering the last option. This "SHOULD" read the level from an applied scriptable object and set a color according to the level, but it keeps throwing errors... any ideas? Everything else is fine, just the outlines...

https://pastebin.com/u3tqGJJV

sour fulcrum
#

(if there's errors we'd need to see them)

#

btw please cache these 😛

wintry quarry
#

also directly modifying fields on another script like that is 😬

rough granite
ripe shard
# rough granite curious is it really that bad to not use data encapsulation?

When you modify the internal state of another object, the other object must be implemented in a way to always expect these changes. The more fields you expose the more difficult this gets. So to contain this problem you expose data as readonly properties and generally only mutate internal state through methods on that object. This way the object can control its internal data consistency.

wintry quarry
tender onyx
wintry quarry
wintry quarry
#

(line 13, what is that?)

#

of PowerUp.cs

tender onyx
#

Says line 13 of powerup (The PowerEffect.Material void), but opening the error goes to my loot script

wintry quarry
#

this is line 13

#

it's pretty clear that PowerEffect is null

#

you need to assign it

#

in the inspector

tender onyx
# wintry quarry of PowerUp.cs

It's assigned from my loot script when an enemy is killed, that way it can randomly select one. Once it's spawned the powereffect sets itself

wintry quarry
#

or you wouldn't be getting that error

wintry quarry
#

Awake runs BEFORE you assign it here

tender onyx
wintry quarry
#

By the time Instantiate is finished running, Awake will have already run and thrown the error

tender onyx
wintry quarry
#

neither

#

make a custoim initialize function

#

Instead of:

lootObj.GetComponent<PowerUp>().PowerEffect = dropped;```
You want to be doing:
```cs
lootObj.GetComponent<PowerUp>().Init(dropped);

And instead of:

    private void Awake()
    {
        pickedUp = false;
        PowerEffect.Material(gameObject);
    }```
You'd do:
```cs
    private void Awake()
    {
        pickedUp = false;
    }

    public void Init(PowerAbstract effect) {
      PowerEffect = effect;
      effect.Material(gameObject);
    }```
wintry quarry
#

some of the naming is a bit confusing to me though

tender onyx
wintry quarry
#

fixed it now

tender onyx
#

So no more error, but still no change to the color

wintry quarry
#

Isn't Level always 0?

slow fossil
#

I have them both in my abstract class

    private void OnTriggerEnter(Collider other)
    {
        print("Something entered");
        if (other.CompareTag("CanBeAttacked"))
        {
            enemiesInRange.Add(other);
        }
    }
    private void OnTriggerExit(Collider other)
    {
        print("Something exited");
        if (other.CompareTag("CanBeAttacked"))
        {
            enemiesInRange.Remove(other);
        }
    }

But it doesn't produce anything in the console

#

same thing when I move the two

slow fossil
#

Do I have to call OntriggerEnter or is it called automatically like Update?

rocky canyon
#

its a physics method.. runs every fixedupdate()

slow fossil
#

I see

wintry quarry
#

it does not run every FixedUpdate

#

but you need to have the correct configuration in the scene, which Box's link will help you check

rocky canyon
#

hmm, didn't know that. so its an event sorta

#

well the engine must know when the overlap happens in order to trigger it automatically.. right?

wintry quarry
#

of course

rocky canyon
#

im actually confused now

#

the physics engine is running in a fixed timestep tho?

#

a tick

wintry quarry
rocky canyon
#

i'll give it a read.. i've never actually read that page.. just referenced the diagram 😅

wintry quarry
#

and yes the physics sim is on a cadence with FixedUpdate

rocky canyon
#

okay.. that makes me feel a bit better lol thought i was fried

wintry quarry
#

I only had issue with you saying "***every ***FixedUpdate"

rocky canyon
#

its just not the Monobehaviours FixedUpdate() tahts doing it

#

ah okay.. ya mb

wintry quarry
#

also FixedUpdate is before the physics sim step, this is after, which is sometimes relevant

rocky canyon
#

aye, honestly never seen/clicked into the contextual links

slow fossil
#

I think the problem is totally unity... And not me haha

slender nymph
#

the issue is likely your setup

#

which object has the rigidbody on it

slow fossil
#

I use some sphere collider to hold everything together

slender nymph
#

okay and which object has the rigidbody on it

slow fossil
#

I have never used Rigibodies
basically, I have a cube with an ArcherBehavior and a ball with a PeonBehavior
I have something like that

abstract class Tower : MonoBehaviour {
  protected List<Collider> enemiesInRange;
  protected SphereCollider rangeCollider; 
  
  protected SphereCollider initiateCollider()
    {
        if (range > 0)
        {
            SphereCollider rangeCollider = gameObject.AddComponent<SphereCollider>();
            rangeCollider.isTrigger = true; // Can detect things
            rangeCollider.radius = range; //size of range

            return rangeCollider;
        }
        else return null;
        
  }
  private void OnTriggerEnter(Collider other)
    {
        print("Something entered");
        if (other.CompareTag("CanBeAttacked"))
        {
            enemiesInRange.Add(other);
        }
    }
    private void OnTriggerExit(Collider other)
    {
        print("Something exited");
        if (other.CompareTag("CanBeAttacked"))
        {
            enemiesInRange.Remove(other);
        }
    }
}

Tower

public class ArcherBehavior : Tower {
  public Awake() {
    initiateCollider();
  }
}

archer

and the enemies have the same collider initialization

slender nymph
#

I have never used Rigibodies
there's your problem.

#

if you would actually bother going through that link i sent before you'd see that a rigidbody is required to send collision and trigger messages

slow fossil
#

Aren't collider enough just for the function enter and exit?

slender nymph
#

there must be at least one rigidbody involved in the trigger overlap to send the trigger message

slow fossil
#

very well

drowsy flare
#

Unity version control keeps nagging me about changes in files that are unchanged. When I diff them they are identical. Is this a known issue? Any workarounds?

slender nymph
#

is it your own files or is it stuff from unity like Text Mesh Pro related stuff? i ask because i recall a recent editor patch fixed an issue with version control noise related to some specific unity stuff

drowsy flare
drowsy flare
slender nymph
#

what version of the editor are you using

drowsy flare
#

I'll try upgrading to latest-latest

rancid tinsel
#

could someone explain the difference between these two?

marsh vale
#

anyone reccomend any good videos to learn unitys new player movement system

slow fossil
#

Any idea why is the OnTriggerEnter and OnTriggerExit is triggered twice for two sphereCollider?

solar hill
#

i think

radiant voidBOT
rancid tinsel
#

man this whole multiplayer thing is so confusing, but definitely a lot simpler than I was worried about

slow fossil
#
    Object n°1
    private void OnTriggerEnter(Collider other)
    {
        print("Something entered");
        if (other.CompareTag("CanBeAttacked"))
        {
            print("and it's an enemy");
            enemiesInRange.Add(other);
        }
    }
    private void OnTriggerExit(Collider other)
    {
        print("Something exited");
        if (other.CompareTag("CanBeAttacked"))
        {
            enemiesInRange.Remove(other);
        }
    }
    SphereCollider rangeCollider = gameObject.AddComponent<SphereCollider>();
    Rigidbody rb = gameObject.GetComponent<Rigidbody>();
  Object n°2
    SphereCollider rangeCollider = gameObject.AddComponent<SphereCollider>();
#

they both have colliders (range set to 1)

#

I suspect it has to do with both edges being detected as entering and leaving

indigo valley
#

Hey everyone! ive been running into an issue with a scriptable object asset i created and cant figure out why, so thought id try some luck asking here.

My asset says that the assocaited script cannot be loaded and to fix compiler errors, but there are no compiler errors, and adding anything to the script and saving, even if its a comment or a blank space, makes the asset work again. But it breaks again during the next project open or whenever i switch scenes.

Any idea what it could be?

Ive tried reimporting all and the file name and class name are the same, all the classes are system serializable

grand snow
indigo valley
#

i have a different scriptable object by itself and that one never had any issues

grand snow
#

If the class definition is in a file with the same name (MyCoolSO.cs -> public class MyCoolSO : ScriptableObject{) it should work fine

#

What you describe reflects what I had in the past when I had the class def share a file with another

naive pawn
indigo valley
grand snow
#

How do you make the assets? CreateAssetMenu attribute?

#

Do newly made assets work correctly?

indigo valley
grand snow
#

can you share the code for the scriptable object class that has the problems?

#

!code

radiant voidBOT
indigo valley
grand snow
#

It doesnt need the Serializable attribute but I see no reason for this to break

#

are you doing anything strange with meta files or asm defs?

indigo valley
#

i dont even need to edit the script itself, editing any script in the project also makes it work again

coral patio
#

Hey knowledgeable people, is it possible to get persistent unique ids for game objects by default? Reason: we have about 3000 collectables and are working on a save system so we need to be able to spawn or despawn them in. Or is there an particular better way I am missing?

Our idea was to write in arras of object with some BSON and other data as a save file

fast relic
#

though the ids do not persist between sessions!

coral patio
fast relic
#

you'd probably have to generate them yourself then

coral patio
#

I feel like I'm dumb this seems such a common use case for almost any game that I feel like Im missing something. Yeah maybe.

fast relic
coral patio
fast relic
sour fulcrum
#

generally any implementation needs to be fairly specific to the game its built for so it's hard to make something general like that

coral patio
#

Okay so I assume best way to go write a custom script which adds a unique id to any object when creating in the inspector is prob the best idea so they can be saved

fast relic
#

that should work fine

timber tide
#

I just generate GUIDs on everything even though Unity does have some utility I prefer to have the control

#

asset IDs are fine though and they wouldn't change between session. Not guarantee if you do patch the game though

coral patio
#

Sounds good guys thanks!

ripe shard
# coral patio Hey knowledgeable people, is it possible to get persistent unique ids for game o...

the standard way is to serialize a per instance-GUID as a string in a field on a root-level component of a gameobject you want to identify. then store those GUIDs in your save. On restore find the objects with those GUIDs and inject the saved data into them. If you want your save-system to restore dynamic objects, you would need to make a asset-lookup and store a unique asset ID next to the instance IDs in your instanced objects that points to the prefab from which they can be restored (this works similarly to how netcode spawns/despawns objects in clients).

onyx geyser
#

well, I spent all day learning the basics for C#, would the next best thing be to look at several hundred tutorials and disect how they go about making their games?

#

now that I can probably vaguely understand how anything works at all in this software?

eternal needle
#

if this is your first language, a day in c# likely isnt going to be that much honestly

sour fulcrum
#

maybe make a calculator in unity 😄

onyx geyser
#

well, i've had prior knowledge, so most of what I learned was more like- getting a bit deeper and learning how it actually works, but I think I might have some confidence in how to make some things

#

Time to make a highly complex leveling system that genuinely doesn't actually work

sour fulcrum
#

Or a calculator 😄

#

then add levels to it 😄

onyx geyser
#

why a calculator?

#

also why're you smiling

eternal needle
#

!learn

radiant voidBOT
eternal needle
#

just realized the link didnt send before

sour fulcrum
#

the smaller the project the better and it's hard to accidentally overscope a calculator. also skill checks you on using unity to handle inputs (pressing buttons) variables (the current values of the calculator) and outputting to text

onyx geyser
#

suppose that's true

#

well suppose I SHOULD ask, how decent of a teacher is W3Schools

#

buddy of mine sent it to me ealier and said it was decent

sour fulcrum
#

as a resource? extremely solid. as a teacher? pretty bad imo

#

I find it very helpful when im new to something and need a pretty isolated, working example snippet of how something works fundementally

onyx geyser
#

so as a newbie it's probably pretty good because it showcases a fundemental process of using it?

#

but outside of that, it's better as just a resource?

sour fulcrum
#

Yeah, it happens to most people so don't take it personally but its very easy for new people to get choose paralysis on mix-maxxing the best possible resource they could be learning from

#

A lot are going to vary in different ways but anything relatively ok is better than nothing

onyx geyser
#

heard

gaunt vortex
#

how do i fix this

sour fulcrum
#

A lot of non-interactive education kinda ends up being teaching how to follow given instructions which can help drill certain ideas in and get comfortable working with stuff but a lot of getting to the point where you can actually think of an idea and start making it comes down to learning how to learn, where you can dumb down your idea into micro steps and determine what you dont know how to do so you can then learn that isolated thing

#

kinda rambly i've been awake way too long 😄

onyx geyser
#

well, Maybe it helps i've been straying a little bit to see how to combine a few of the things I learned, though it made me wish I knew more about User controls

#

it didn't much on ReadLine(), I tried to figure out how to use an If else with ReadLine and couldn't get it, it was one of the few that got me

#

as well as a lack of information on what exactly Type Casting is used for, other than that it's "rarely used"

#

it kinda lacked on If else and boolean, restricting it to numbers and never really interacting with anything else

sour fulcrum
onyx geyser
#

Inheritence, like, the idea of passing down something? A statement passing down information to another statement kind of deal?

#

I don't wanna get ahead of myself on guessing

sour fulcrum
#

kinda but more in the context of something as a whole

#

can i assume youve played minecraft

onyx geyser
#

yeah

gaunt vortex
onyx geyser
gaunt vortex
#

i closed the hub and ran administrator but that didnt do anything

sour fulcrum
#

so for example mobs, a lot of mobs share the same fundamentals (moving, being hit, doing stuff etc. etc.)

instead of making classes for each mob and redoing all that kinda stuff, you can make a "base" class for Mob and then "inherit" "from" Mob in order to use it as a foundation and build ontop of it

but yeah this is probably slightly abit ahead of where your at so no stress if it's abit much

onyx geyser
#

ok.. have you looked online for any information on this specific quote?

onyx geyser
#

it's a base you can work off of right?

#

I think i get it, it's like an empty character you can apply a model, animation, and stats too, in the gamey kinda way of putting it

#

right?

sour fulcrum
#

methods and the class itself yeah. you probably don't need to know the specifics of how that works just yet but the broad idea is nice to be aware of

sour fulcrum
#

A Microwave might inherit from Appliance which might inherit from Furniture etc.

onyx geyser
#

so it's layed "what you can do, i can do" type of thing

#

that would explain why I didn't really get it

#

I think i still managed to use it at some point in my strange code

#

if it's the same thing were thinking of

sour fulcrum
#

more specifically "what you are, i am (and potentially more)

worthy veldt
onyx geyser
#

I think I get how that works a bit better

naive pawn
young drift
#

Hi I'm beginner in shader, I'm trying to make a simple linear gradient in Unity in shader code that have controls with the start and end but when my _GradientEnd is 1, and my start is 0, my expected output should be all red as that's my end color, cause I assume 1 should be like 100% but why is my output still like a 50/50 gradient?

north kiln
worthy veldt
tawdry valley
#

Hi, i am trying to build a rigidbody charachter controller. I am not sure should i override linearVelocity or addForce. Which is better for movement?

timber tide
#

setting velocity is for very specific scenarios. You wouldn't use it as the main driver to your controller

#

because every time you set the velocity you forgo any forces that were placed upon that body

#

Friction, dampening, elastic behaviours wouldn't even apply

tawdry valley
#

But many tutorials and AI examples i generated doing the movement method like that

midnight plover
#

AI examples is a bad way to learn. They can help you if you know what the output means. tutorials are depending on what you are trying to achieve. Sometimes it makes sense to fully control the velocity, sometimes it does not.

keen dew
#

It depends what kind of movement you want and what is moving (platformer character, car, etc.) Setting velocity directly gives precise control over the movement, but it won't look natural without a lot of extra work.

tawdry valley
midnight plover
#

!learn

radiant voidBOT
cedar peak
#

my restart button isnt working no matter what i do
can i share the project to anyone to see if you are able to fix it

midnight plover
cedar peak
#

its supposed to respawn the player
this is the code public void Restart()

     Debug.Log("Clicking restrt.......................");
     Scene currentScene = SceneManager.GetActiveScene();
     SceneManager.LoadScene(currentScene.name);
 } ```
it wont work no matter what
midnight plover
#

!code

radiant voidBOT
midnight plover
cedar peak
#

its showing everything else is just fine

#

but when i click it wont respond

#

even the debug message isnt showing up

midnight plover
#

How did you attach the method to your button then?

#

And what is the "button". UI? 3D? give some info about the setup pls

cedar peak
#

i wrote it in game manager unversal 2d

#

platformer

midnight plover
cedar peak
#

yes standard no errors

midnight plover
#

Does your button react to your mouse hover?

cedar peak
#

no

midnight plover
#

is there an eventsystem in your scene?

cedar peak
#

how do i tell theres nothing in the hierarchy

midnight plover
#

How do you know there is no cat in a room...

cedar peak
#

..im still learning

#

its fixed

#

1 more thing

#

when the game starts if i try going left(jumping off ) it wont let me and theres no colliders in the air on the left so i have no clue whats stopping me

midnight plover
#

Again, without code, its just a guessing game.

#

!code

radiant voidBOT
cedar peak
midnight plover
#

yep, thanks

warped valve
midnight plover
cedar peak
#

yes but only at that certain place otherwise i can move left just fine

midnight plover
midnight plover
cedar peak
#

i can go further left from the grass

midnight plover
#

are you sure, there is no small 2d collider stopping you at whatever point?

cedar peak
#

yea id figured the same but if i try to jump i acts like theres a wall of collider
in the image im moving left and somethings stopping me

midnight plover
#

Just for testing. Can you move your visual level to the left or right and see, if the invisible border goes with it?

worthy veldt
#

!code

radiant voidBOT
split mason
#

Hi!!
so i got started with multiplayer, people around me suggested using Photon Fusion 2, but i am stuck as their documentation doesnt really explain things in details, can someone suggest some sources to get implementation practical guidelines for photon fusion 2?
(plus dont really know where to post this kind of discussion, if i am not allowed to do it here then do let me know.Thanks.)

chrome apex
#

My player is a rigidbody that has a collider that's horizontal to the ground.

It's comprised of two capsules that don't touch and they make a "T" shape.

Anyway, when I move push the player forward, it often catches on the side-to-side part of the collider and starts flipping towards the ground.

What should I do here? Increase angular drag (and maybe drag) and add more forces when moving/rotating?

I don't think switching the collider to a box would help with that. Maybe I'd need to remove the upper part of the T collider?

echo ruin
hardy prairie
#

or use probuilder to merge them if you still want the rotation

midnight plover
#

#1390346492019212368 could also be the better palce for general questions about networking if you dont have a specific code question

split mason
midnight plover
split mason
midnight plover
#

The difference between 3d and 2d is not really relevant for photon afaik. If you need to clamp 2d positions, you basically sent a vector3 with z = 0 for example. So thats more up to general coding than networking with photon or netobjects or whatever multiplayer variant you chose

split mason
midnight plover
split mason
#

thanks thanks!!!

chrome apex
chrome apex
#

Can't freeze them

rough granite
naive pawn
wraith delta
#

hello, i have this code, shot a ray from the player to the middle of the screen, that's working while the player is centered aswell but i have an offset on the player with cinemachine

    private bool TryGetRaycastHit(out RaycastHit hit)
    {
        Ray screenRay = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
        Vector3 rayOrigin = origin.position;
        Vector3 targetPoint = (screenRay.origin + screenRay.direction * 100f);
        Vector3 rayDirection = (targetPoint - rayOrigin).normalized;

        //Debug.DrawRay(rayOrigin, rayDirection * distance, Color.red, 1f);

        return Physics.Raycast(rayOrigin, rayDirection, out hit, distance, mask);
    }

the ray should go from the player to the center of the screen, any solution?

tried transform.TransformVector() but it doesnt work as expected

chrome apex
chrome apex
naive pawn
keen dew
hardy prairie
#

Then they will act as one object

#

But if you want to seperate them then it wont work

wispy bison
#

Hi, I'm a beginner and I need some guidance.

I'm trying to make a system where a character launches projectiles randomly from a "deck" of cards. Each projectile has physics and the same set of stats but with different values like speed, power, etc.

Later on, I want to program a menu where the player can see their full deck with all the different projectiles and add new ones.

Right now the projectiles in the "deck" are prefabs in a list. Is there a better way to do this? I've heard scriptable objects being talked about but I'm not sure what that is.

I just want to know if I'm on the right track or if there's an even better way to accomplish this before I go down a rabbit hole. Thanks!

frosty hound
#

SOs are containers that hold data. If you're doing something like an inventory or item system (including cards), they're a good usecase because you can create an SO for each thing and define a bunch of the values of it.

#

Such as an Item SO that lets you give it a name, price, description, etc.

rough granite
wispy bison
#

I see. Right now I have all the data in a single script.
But with an SO the object would have its script that controls all the physics, and then a separate Scriptable Object attached to it for all the stats?

rough granite
#

But you'd probably want a controller script that has a list of every SO card and a single prefab that can be instantiated with anyone of the SOs

wispy bison
#

Thank you! So I can keep the list with prefabs that I have now, and when I want to do the inventory screen, that's when I'd start using the scriptable objects?

frosty hound
#

The SO doesn't "control" anything, it's purely a data container.

#

A card in your case would be given the SO that contains its information (as a reference would be easiest). Then your game logic would use that to do whatever it needs to.

When the card "attacks" for example, you can pull out the damage values from the SO on that card to calculate the final outputs.

wispy bison
#

I guess where I'm confused is that what I'm drawing from the deck are random projectiles prefabs. So where could I use the SO? Like in the stats of the projectiles, or in the inventory showing all the projectiles?

frosty hound
#

If youre projectils are wildly different, then keeping them as separate prefabs and just putting all that information directly on them as properties or even hardcoded into their unique controller scripts, is fine. I don't think you necessarily need SOs here unless you want an easy to modify their individual design values without opening the prefab.

#

SOs really shine when you have a template prefab that you modify/dress up based on the SO its given.

wispy bison
#

Got it! Thank you

wraith delta
#

@keen dew yeah, i mean, its working, the problem is the camera offset applied to the player

keen dew
#

Right. After the first raycast you need to do another from the player character to what the first raycast hit

#

Note that this is a problem that doesn't have a satisfactory solution, only a lot of tinkering to make it work somewhat satisfactorily

wraith delta
#

i was trying to add the offset directly to the target, or the origin so the ray goes straight, but after that it goes crazy

#

is taking the target from the world and not the 2d canvas space, like if the ray is long enough it will reach the center of the screen inside the world

keen dew
#

There is no center of the screen inside the world. It's a continuous line from the camera to infinity

#

You have to pick a point from that line (which is what the original raycast is doing)

amber warren
#

Hi im trying to make a function in a vr game where two flasks with different colour liquid can be mixed together howevr i cant get the script to work

radiant voidBOT
# hexed terrace !ask

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #🌱┃start-here

hexed terrace
#

!code

radiant voidBOT
bitter pine
#

how do i turn the playback rate of an audisource up when a bool is true?

#

so ive got a sprinting system and i want the speed of an audio clip to speed up when running, but there doesnt seem to be a playback rate var of anykind?

rocky canyon
#

that can be done w/ really short footstep sound clips..
where u control when they play..
so ur code will play them quicker together when sprinting

#

[] [] [] [] [] vs
[] [] [] [] []

polar acorn
bitter pine
#

i shall give it a try

rocky canyon
# rocky canyon [] [] [] [] [] vs [] [] [] [] []
    [Header("Step Intervals")]
    public float walkInterval = 0.6f;
    public float runInterval = 0.3f;

    void Update()
    {
        if (Input.GetKey(runKey))
        {
            currentInterval = runInterval;
        }
        else
        {
            currentInterval = walkInterval;
        }
        
        // then a timer
        timer += Time.deltaTime;

        if (timer >= currentInterval)
        {
            PlayFootstep();
            timer = 0f;
        }
    }```
something like this is what i was referring to @bitter pine you can also use pitch as Digiholic mentioned to compliment it
bitter pine
#

ohhhh

#

i understand that actually

rocky canyon
#

so ur play short clips at different rates

bitter pine
#

i actually did already split them up

#

thanks!

rocky canyon
#

good stuff good luck 🍀

bitter pine
#

though i changed up the way they split, mine wait till its done, play a coroutine with waitforseconds then play the next, is your way better in some way?

#

or?

rocky canyon
#

no.. not necessarily.. i wouldn't ever say one way is better than another if they achieve ur desired outcome

bitter pine
#

kk

rocky canyon
#

i was merely showing an example of what i was trying to explain

#

you do you mate 👍

rocky canyon
#

if its anything more than "you hit the timer limits -> do the thing -> and reset the timer"
i'll use a coroutine

night raptor
#

Not that it probably makes any difference in this case, but I generally prefer doing timer -= currentInterval. Just zeroing the interval essentially adds half a frame delay in average (so do coroutines I assume, unless specifically taken into account). If the game lags immensely the sounds could in theory get stacked for upcoming frames (if subtraction was used) so timer %= currentInterval would probably be fine too. I assume we don't want to have a loop either to play multiple sounds the same frame so the modulo should just discard the extra intervals that might be stacked up in the timer variable.

#

Again, doesn't make much difference usually, but just a small detail that is very easy to add

rocky canyon
#

ya, we all have our timer preferences

#

some ppl like adding the next interval onto the limit

#

others like to reset timer completely..

#

some people like counting up and some people like counting down lol

night raptor
#

In theory there is a small difference in framerate independence so it's not only about preference but it's mostly notable for things happening in very fast intervals.

#

It's bit similar to how velocity += acceleration * Time.deltaTime isn't fully framerate independent but most don't care taking that into account (even though it's not particularly hard) due to how little the difference is. Well that is framerate independent way to increase the velocity but if applied like that to a moving object, it will not be

drowsy tiger
#

has anyone have experience with "resistance" in joints? I have a configurable joint, which acts like a hinge joint, inherently a motor.

What I'd like to do, is, prevent the connected body to NOT rotate, until the motor is rotating it. The motor is just a very simple clockwise/anticlockwise input setup. But whatever the motor is controlling, sometimes changes its initial configuration, due to gravity. which makes sense. I'd rather not disable gravity on the controlled rigidbody, but resist it

I've tried zeroing out angular velocity, but it kinda just falls slowly. I don't want to actually apply a countering force, because when I tried this, this ends up creating forces of its own.
Playing with confiugrableJoint.targetRotation has yielded a nicer results, but I have no idea how to actually calculate it and set it. Just Quat.Angle(initial, current), seems to give the correct angle, but its not very accurately simulating

rocky canyon
hot wadi
#

This is not very code-related

night raptor
# rocky canyon so what ur saying is if i wanted complete accuracy i shuldn't be resetting my ti...

Yes, setting it to 0 will overwrite what you had already cumulated in timer. Afaik that should add half a frame of delay in average to each time you are resetting the timer. Let's say your game would run 50fps (deltaTime = 0.02) and you wanted to reset the timer 10 times a second. You would end up resetting the timer every 0.011 seconds by average (0.1 + 0.02 / 2.0). Often not impactful but something to keep in mind to know where it is fine and where not.

rocky canyon
#

sounds to me he's manipulating the joints via code.. so its 50% related.. but I posted a response in #⚛️┃physics cuz they probably have a better hang of joints in general and all the physics components

rocky canyon
#

even has a nice flow-chart Unity’s time logic definitely gonna add this to the bookmarks

#

timer drift lol

night raptor
# rocky canyon ah, i kinda knew this but never had anyone explain it to me 👍 thanks for the i...

Usually my timers would look like this to also take care of the case where you need to do that whatever thing multiple times a frame (especially important if interval < expected deltaTime):

void Update()
{
    timer += Time.deltaTime;

    //while can be replaced by íf-statement if we won't have timer >= interval * 2
    //due to high deltaTime or/and low interval
    while (timer >= interval)
    {
        DoWhatever();
        timer -= interval; //the important part
    }
}```
rocky canyon
#

ohh i think i had a eureka moment... soo its like if the timer passes the threshold.. but is not an exact divider you'll have some "remainder" that gets yeeted

rocky canyon
#

ahh i get it now 👍 thanks friend

drowsy tiger
#

if we're discussing on that level of delta, that means the second time around that remainder actually adds up to your timer, and hence its a little faster the second time around

rocky canyon
#

yup, makes perfect sense to me now.. just never have used it for anything precise enough to notice

#

i've heard stories of when you run a game for hours on end you'd def notice a difference.. if ur timers have been running since bootup

#
void Update()
{
    float dt = Time.deltaTime;
    totalTime += dt;
    minuteAccumulator += dt;

    while (minuteAccumulator >= interval)
    {
        Debug.Log($"A minute passed! Total time: {totalTime:00}s");
        minuteAccumulator -= interval; // the magic part
    }
}```
#

yea that -= interval is smart 🧠

#

imma do my timers like this from now on

#

trying to think of any edge cases where this wouldn't work perfectly fine for me..

#

but can't think of any off-hand.. soo imma roll with it

#

instead of: resetting timer to 0
we're basically resetting only the part we used keeping the remainder to carry over on the next duration,
neat 👀

night raptor
#

precicely

rocky canyon
#

only took me 4 years and a handful of months to figure out something soo basic 😆

#

i think i've been cautioned before but was always too ankles-deep in work to consider figuring it all out.
im pretty sure they were like "it'll work for basic simple timers (only controlling (1) thing).

#

glad i stopped this time and looked into it

#

ohh.. and the while() instead of the if() makes more sense too

#

didn't think of that until just now.. it would correctly log (2) times if we had some stupid long lag spike or something

#

instead of the if() just jumping over one

night raptor
# rocky canyon instead of the *if()* just jumping over one

Well, it will keep the extra time in the timer and take care of that in the next frame but the issue arises when the game is constantly running on deltaTime more than interval in which case the if will execute every frame but the timer will keep going up which is often not wanted. In this case however when what we want to do is play a sound effect, we probably don't want to fire the same sound effect multiple times on the same frame even though we would be behind the schedule. Also trying to catch up by playing the sound effect in consecutive frames after a lag spike would probably not sound very pleasent either. That's why I suggested using timer %= interval which would just remove all but the remainder. Depends on the case what we want to do, but in most cases I choose the while together with -=

rocky canyon
#

good stuff.

#

yup, so it just depends on teh use-case of the timer 🙂

#

"all things are relative" - someone i bet

night raptor
# rocky canyon i've heard stories of when you run a game for hours on end you'd def notice a di...

Something that can usually be taken into account in the code but the issue is essentially that single precision floating point values are only precise up to around 7 significant digits. If you need to present the current time since start using float you would be limited to millisecond precision once 10k seconds have passed (around 3 hours). In some math intensive calculations that might be enough to cause noticeable defects. For that reason there's also the Time.timeAsDouble and such methods in the Time class which use the double precision floats (double) with which you will never in million years run out of precision. Too bad most GPU's only support single precision floats so to avoid these issues on shader effects to which time is passed requires some tricks (like resetting the time passed by intervals that don't cause a flicker). note that the 10k seconds and millisecond calculation is only accurate to a magnitude level, the point was just that on thousands of seconds, you would start getting bit limited by precision

rocky canyon
#

i did used to have a GameTick script that kept up with multiple frame-rates / tick-rates
and would just fire off events that all my other systems relied on..
i used it mainly for AI / Enemy Sensor Arrays..
like it could think x amount of times every second...

#

it gave a bit of "randomness" to the enemies movements

#

i think i'll redo that system using that while method just for exercise

flint rover
#

is there anyone who wouldnt mind hopping in a call with me to help me out?

rocky canyon
#

you'd need to use an external website to get support groups or..
edit: Unity Developer Community has VC channels.. but this is more of a community channel..
you ask out in the open publicly..
a. - to get help from everyone
b. - to help everyone that way someone can search thru the conversations and find useful information for themselves.. if they're having the same problem

radiant voidBOT
#
<:error:1413114584763596884> Command not found

There's no command called colab.

edgy sinew
#

⭐ Hello guys, what is your recommendation for Hands IK on 2-handed weapons? ⚔️

I've set up some "rotation & position" config so, any item can attach fine to the Player's right hand,
But with 2 handed weapons, well, now there has to be a real-time IK target indicating which spot on the weapon to hold (left hand)
And furthermore then aiming the weapon, totally breaks both hands IK, rotations etc, and looks terrible...
Thanks for your help guys... trying to avoid needing like 4-5 config rotations per weapon lol

eternal needle
rocky canyon
#

put a target gameobject on the weapon.. should be able to set the IK's target or hint to that

edgy sinew
rocky canyon
#

👍 thanks for the headsup tho 🙏

rocky canyon
edgy sinew
rocky canyon
#

i can look for alternatives a bit later during lunch.. if its not cool enough for ya 🤪 lol

edgy sinew
rocky canyon
edgy sinew
#

Actually my "config per object" would then hold references to those invisible hint objects

rocky canyon
#

and break out ur rotation and stuff in something different

#

you using Unity's Animation Rigging package?

edgy sinew
flint rover
rocky canyon
#

or something like FABRIK

rocky canyon
#

i love using it for procedural animations

#

think like a Kraken's tentacle

rocky canyon
edgy sinew
#

it's so great. like to make my sprint animation more dramatic, i just tilt the spine1 spine2 spine3 forward lol

rocky canyon
#

so it says thisThing.DoFunction()
but the code is like umm.. which thisThing? i can't locate it

flint rover
edgy sinew
rocky canyon
edgy sinew
#

Sharing data between different scripts?

rocky canyon
rough granite
rocky canyon
#

ohh that could be it ^

flint rover
edgy sinew
#

And wouldn't it have to be created, if there is no instance?

rough granite
rocky canyon
#

it was flippity flopped lol

edgy sinew
#

Or technically, as a MonoBehaviour, the one object it's placed on, would be the instance

flint rover
#

i also tried without the if statement completely and its just instance = this

edgy sinew
rocky canyon
#

is the script in the scene?

flint rover
edgy sinew
rocky canyon
#

5 years isn't that old tbh but it could be a faulty tutorial

rough granite
flint rover
# edgy sinew Send it bro i'm sure i have a better one

Ever wanted an Easy solution at coding a 2D Melee Combo System inside the Unity Game Engine?

Correctly coding it can be frustrating: the majority of solutions you'll think of or find on the internet will be either overly complicated or not even work.

No worries! WIth this tutorial you'll be able to code your own 2d melee combo system in unity ...

▶ Play video
rough granite
flint rover
rocky canyon
#

is it in your game?

night raptor
# eternal needle itd be a bit rare to run into this case considering the max delta time is 0.33. ...

Only case where this would actually be much of an issue is where the interval is very short (potentially much shorter than we expect deltaTime to be). Ended up in a bit of tangent from the way I personally like to do timers, in most cases I just figure it wouldn't hurt changing an if to a while. Depends on the actual use cases whether this would ever make any difference in practice, in most cases not. As I explained later, it also doesn't always even make sense to do the same thing multiple times a frame

flint rover
rocky canyon
#

it wont work if it stays in the Project Window.. and never actually added to the game.. or on a gameobject

flint rover
rocky canyon
#

doesn't have to be a prefab.. but it must be in the Hiearchy

rough granite
edgy sinew
#

Usually things are created in Awake / Start, or static or something else whatever
Then you need references to those things

Here it seems like you are trying to get a particular instance of the AttackScript,
The question is, from where? @flint rover 🤔

rocky canyon
drowsy tiger
#

statemachinebehaviours are attached on animator states inside the animator window

flint rover
#

if it helps im at 10 mins on the youtube vid i sent before

rough granite