#archived-code-general

1 messages · Page 280 of 1

cosmic rain
#

How do you initialize the native array?

keen smelt
#

So running in Update, I run this:

#

in CompleteProjectileHits(), literally it stards with handle.complete(), and normally place it in Late Update. I shoved it in there and no errors, so it runs in the update.

#

I hope that makes sense. Thank you in advance any advice and for your time!

dense tusk
keen smelt
#

got it! Doing it! sorry!

ashen jasper
#

Yea I got it but I didn't do waypoints. I simply made collision so it would update the z axis

cosmic rain
keen smelt
#

So I'm sure I'm just doing something wrong? It seems OK to me but what do I know lol

cosmic rain
keen smelt
#

for context, points to line 131 which is starting the for loop. handle.Complete(); for(int i = 0; i < raycastCommands.Count(); i++)

#

the line immediately after I complete it. I dispose after the loop

cosmic rain
#

I think the error implies that there's double deallocation going on. Maybe that code runs again after the arrays were already disposed?

keen smelt
#

ah god dammit

#

yes 100% you are right

#

I'm a moron

leaden ice
keen smelt
#

I was running it when no job was scheduled

leaden ice
#

Ah you figured it out

keen smelt
#

and I thought my logic was good to be like "hey do this if I have a job"

#

but no

#

for I am dumb

#

THANK YOU @cosmic rain

#

I just added a bool for when I scheduled the job and checked for it, and reset it after I cleared it. I... don't know what I was doing before but it was wrong.

#

sigh

#

not sure why they let me drive a car

#

yet here I am

#

thank you all, much appreciated!!

#

Hope you all have a good night

cosmic rain
#

Well, we all make mistakes

keen smelt
#

My wife reminds me daily, yes lol

naive lake
#

!code

tawny elkBOT
naive lake
#

Hey everyone, so in my ball throwing game, i'm trying to make it so that when my player releases space,, the ball releases from the player's hand and scores a point. I'm having an issue with releasing the ball from the player's hand. Here is my ball holding and throwing script: https://hastebin.com/share/sayujacadi.csharp

fervent furnace
#

do you have multiple balls on scene
btw sounds code beginner

naive lake
#

Sorry, I'll post it in there next time

#

No, just one

fervent furnace
#

click left button->hold down space bar->release space bar->release left button, then the ball wont being thrown?

naive lake
#

Nope

#

The ball is released tho

#

I think the if section stops being true once I release the space button and the "isHoldingBall" becomes false

#

But I'm not sure how to do it any other way

fervent furnace
#

you have 6 if blocks here, which one?

naive lake
#

The last one on "ThrowBall"

fervent furnace
#

HoldBall.isHolding becomes false once you release the left button or release the space bar, what is the problem?

naive lake
#

I think that since the ballRb.AddForce does not work because isHoldingBall becomes false

#

Or is that not how if commands work 😅

#

Either way, do you have any idea on how to make it so that the ball will have the force added onto it?

#

The reason I had the ball release from the player, was so that it wouldn't stay in that spot

fervent furnace
#

oh i see the problem, try apply impulse force

naive lake
#

What does it default to?

#

without applying impulse force?

fervent furnace
#

by default forcemode.force

#

v=v+f/m* dt

naive lake
#

So that, didn't fix it...

#

It still releases the ball, and doesn't add the force

#

It might be a seperate issue, I tried this and it didn't add any force anyways

fervent furnace
#

normalize the direction at first, then try to multiply it with a large value eg 100000 to see if the ball moves
i think the isholding ball is not the cause

naive lake
#

I'll do that in a second, but do you think it has to do with the ballForceDirection?

fervent furnace
#

yes

naive lake
#

Like this?

fervent furnace
#

yes

naive lake
#

Unfortunately, that did not fix it

fervent furnace
#

btw you dont need to declare everything to be class fields
post the rigidbody setting

naive lake
naive lake
fervent furnace
#

mistypo

tawdry jasper
#

Was reading someone's dependency injection utility and they said it supports monobehaviours and components. What is a https://docs.unity3d.com/ScriptReference/Component.html and how would you use it? Any monobehaviour script you write you then interact with GetComponent or AddComponent, so how do you interact with an actual Component classes, is there some common real world use case for them or is it just an implementation detail of monobehaviours?

fervent furnace
#

try disable the part that moving ball transform

// Calculate the desired position based on camera's forward direction
Vector3 targetPosition = mainCamera.transform.position + mainCamera.transform.forward * distance + Vector3.up * height;

// Set the position of the object
transform.position = targetPosition;

// Make the object look at the camera
transform.LookAt(mainCamera.transform);
```though i think it should not make any effect after release the space bar
naive lake
#

That whole part?

fervent furnace
#

oh wait, is this script on your ball?

naive lake
#

Yup

fervent furnace
#

then```cs
ball = GameObject.FindWithTag("Ball");

naive lake
#

Oh lol

#

I think I was planning to put it on the player and switched halfway through

#

OH WAIT

#

So I'm planning to have multiple balls in the fuuture

#

I think that was in plan for that

#

But I know that'll require some other stuff too

#

I just want it to work in this way first so I have a baseline on what I need to do

#

Anyways, did u find any solutions to the ball having the force applied to it?

fervent furnace
#

not moving the ball transform
but after moving it the ball should still move since it velocity is not zero

naive lake
#

Sorry, but I don't understand.

fervent furnace
#

comment out the code i posted

fervent furnace
#

the part that moving the ball transform

naive lake
#

So I did these 2 things

#

And it still does not fix it

#

Do you have any suggestions on changing the ballForceDirection (if that's the issue)

fervent furnace
#

reverse the direction

#

player--->ball
dir=ball-player

naive lake
#

I tried it with and without commenting the code, but it did not fix the issue.

fervent furnace
#

apply a constant force
is there any other script modify the ball transform?

fervent furnace
#

dir.normalized*10000, dont take heldtime into account

naive lake
#

That didn't work either...

#

Oh

#

Could it be because it is grabbing it's own transform.position

#

In that case, should I put the script on the player?

naive lake
fervent furnace
#

the ThrowBall is not in player but in the ball?

naive lake
#

Yes

#

Moving it fixed the issue

fervent furnace
#

then the direction vector always zero

naive lake
#

Yup

fervent furnace
#

i think it is on player at first

naive lake
#

I have moved it onto the player now, and it fixed the issue

#

However

#

Whenever the ball moves, it moves in a downward direction

#

*forwards and downwards

#

Nvm, the main issue is resolved and tweaking should fix these minor things

#

Thank you for your time!

golden lichen
#

is there supposed to be a difference when assigning sprites to a spriteRenderer vs a UI image? I'm in a situation where I have to create a sprite from an SVG, but the sprite only seems to be visible on spriteRenderers and not UI images

    void Start()
    {
        List<VectorUtils.Geometry> geometries = GetGeometries();

        Sprite spriteFromSVG = VectorUtils.BuildSprite(geometries, pixelsPerUnit, VectorUtils.Alignment.Center, Vector2.zero, 128, flipYAxis);
        //This doesn't work
        image.sprite = spriteFromSVG;
        //This works
        spriteRenderer.sprite = spriteFromSVG;

        //These both work
        image.sprite = spriteInspector;
        spriteRenderer.sprite = spriteInspector;
    }

    private List<VectorUtils.Geometry> GetGeometries()
    {
        using var textReader = new StringReader(svg);
        var sceneInfo = SVGParser.ImportSVG(textReader);

        return VectorUtils.TessellateScene(sceneInfo.Scene, new VectorUtils.TessellationOptions
        {
            StepDistance = 10,
            SamplingStepSize = 100,
            MaxCordDeviation = 0.5f,
            MaxTanAngleDeviation = 0.1f
        });
    }
#

weirdly enough, assigning a sprite from the inspector seems to work just fine for both

#

settings on UI Image

#

there is clearly a sprite (when I click on source image), but it's nowhere to be seen

golden lichen
#

I also have the option of converting a dataURL (base 64) string to a sprite, but I had no luck getting that to work either

faint nimbus
#

I already have the code, I just dont know how to make something bigger or smaller using the same object when interacting (without hiding or setting to active), or should I just use set active?

#

functions are confusing UnityChanThink

spring flame
#

How do I apply uniform scale whenever scale gizmo is used? For example if someone drags any of the x, y, z handles I want to set the scale to Vector3.one * <scaled axis>

#

ideally I would like to disallow even using the scale gizmos for each axis separately for such objects... but I doubt I can do that

#

Is there some smarter way than keeping track of previousScale and comparing each component separately in OnDrawGizmos/OnGui or something?

golden lichen
#

I figured out the dataURL conversion wasn't working because the mime type is gif, and that doesn't work. I had to find a new library that can encode png and jpeg

#

but the whole svg thing is still a mystery

dawn nebula
#

Any tips of how to get more "organic" following behaviour? Right now each goober just attempts to path straight to its designated point in the formation. The formation itself rotates towards the player and follows them if they get too far away.

wicked scroll
# dawn nebula Any tips of how to get more "organic" following behaviour? Right now each goober...
  1. a more organic shape for the formation would probably help (and i'd space the dudes out more with some variance since they are unnaturally stacked)
  2. if you give them some movement animation (bob up and down maybe), that would add some organic noise to the mass
  3. you could also give them different/varying speeds and let them push each other out of the way so that they don't feel so monolithic
    just some random ideas...might be worth looking at what the pikmin games do or how schools of fish move, depending on what behavior you are looking for
dawn nebula
#

I kinda want/need them to be this crunched though.

#

I'd like... 100 of them >_>

#

and this is only 20

wicked scroll
#

if you can put jiggle bones on the antennae that would add a lot

dawn nebula
#

that's the plan

jaunty ether
#

Hey everyone, do you know this pack? I have a small issue with the ,,Fixed joystick" script. I want to change something in the code (made something public) but the code looks empty (in the inspector everything looks normal). If you guys have that script it will be awesome if you will send that.

sonic swan
#

this is a dumb question

#

but how do i fix thos

fervent furnace
#

fix what?

sonic swan
#

basically the object ref not set to obj error occurs becuae of the lm line

#

the ground info 1 bit is the thing causing the error

fervent furnace
#

you only check groundinfo but you didnt check groundinfo1

sonic swan
#

truee

#

im a silly billy

light pond
#

How to check if certain object or tilemap is under mouse?

#

Or check if certain object with tag

#

please...

latent latch
#

go through the API

#

I'd expect you'd have to raycast onto it

light pond
#

maybe i can do on trigger enter

#

oh wait thats something else

nocturne wyvern
#

Hello!!

I have a simple panel for entering text and sending a message (in the first video)

there is such a problem

I have a script that controls the position of the panel depending on the size of the keyboard using the OnSelect and OnDeselect events

due to the animation of the panel shifting, when you try to click on the send message button, it does not work

How can I make it so that I can:

  1. click on the send message button
  2. do not move the panels when you click on the send button or gift button
#

Script that move my panel up and down

public class KeyboardHandler : MonoBehaviour
    {
        [SerializeField] private InputFieldView inputField;
        [SerializeField] private CanvasScaler canvasScaler;
        [SerializeField] private RectTransform moveRoot;
        [SerializeField] private float moveUiSpeed;
        [SerializeField] private float testHeight;

        private Tween _moveDownTween;
        private bool _keyboardIsActive;

        private void Awake()
        {
            inputField.OnSelect.Subscribe(OnKeyboardActivated);
            inputField.OnDeselect.Subscribe(OnKeyboardDeactivated);
        }
        
        private void Update()
        {
            if (_keyboardIsActive)
            {
                var rate = canvasScaler.referenceResolution.y / Screen.height;
#if UNITY_EDITOR
                var height = testHeight * rate;
#else
                var height = SoftwareKeyboardArea.GetHeight(true) * rate;
#endif
                var anchoredPosition = moveRoot.anchoredPosition;
                var targetPosition = new Vector2(anchoredPosition.x, height);
                moveRoot.anchoredPosition =
                    Vector2.Lerp(anchoredPosition, targetPosition, Time.deltaTime * moveUiSpeed);
            }
        }
        
        private void OnKeyboardActivated()
        {
            _keyboardIsActive = true;
            _moveDownTween?.Kill();
        }
        
        private void OnKeyboardDeactivated()
        {
            _keyboardIsActive = false;
            _moveDownTween?.Kill();
            _moveDownTween = moveRoot.DOAnchorPos(Vector2.zero, 0.1f);
        }
    }
#

this is my send button

#

I try to add simple filtration, that check current selected object and if this object is my Send Clickable view Select input field again, but in this case my currentSelectedGameObject is always "input_field"

If I check currentSelectedGameObject when Click to my button I have null in EventSystem.current field

unreal temple
#

I have no mobile experience, but I think maybe you can set the button so it can't be selected

#

You could also try making the button something that isn't a Selectable (for example an Image) and add a custom IPointerClickHandler on it

#

That way it will never be the currectSelectedGameObject

round violet
#

is there a limit of iteration inside a while loop ?

i would like to run a coroutine that does stuff in a while true loop for the whole game

fervent furnace
#

no

round violet
#

perfect

#

ty

simple egret
#

As long as you yield in the loop, your game won't freeze. Always make sure all code paths in a loop hit a yield

#

Else you'll freeze your game

brittle haven
#

How can I change the width and height of an object in RectTransform Component in script?

simple egret
#

Alter its .sizeDelta vector

vivid heart
#

What do you think about having 1 point of update, lateupdate, fixedupdate in the project, is it worth it?

left timber
#

hiii

naive swallow
left timber
#

i need some helps in writing a shader for a 2d pixel art style water it would be glad if someone direct me to the relevant sources!

naive swallow
#

Also makes pausing pretty trivial to do which is normally a huge pain

left timber
#

i am new to unity but experienced in other game engines but never wrote shaders before

#

just need a direction where i can start

latent latch
#

youtube

#

unity water shadergraph

hard viper
#

I have an interface for special cases, with a function that does something something, and then returns true/false to let the function that invoked it know if it should also continue with non-special case code.
This feels… inelegant. Am I doing something dumb?

left timber
latent latch
little meadow
latent latch
#

That's more 3D though, but some similar concepts for 2D

hard viper
#
///<summary>Update preview based on the state of building input.</summary>
public void UpdatePreview(BuildingCreator.BuilderInputState inputState) {
    UndoOldPreview(inputState.lastGridPos, inputState.selectedObj, inputState.buildModeType);

    if (inputState.selectedObj.customDrawLogic != null
        && !inputState.selectedObj.customDrawLogic.DrawPreview(inputState)) return;

    switch (inputState.buildModeType) {
        case BuildModeIndex.Normal: DrawPreviewDraw(inputState.selectedObj, inputState.currentGridPos); break;
...
...```
naive swallow
vivid heart
hard viper
little meadow
hard viper
#

so does true mean it successfully drew a preview, and we’re done, or true that we need to continue to normally draw preview as well?

little meadow
#

same as all Try things - true on success of the operation

#

it doesn't know what the outside is using the result for

hard viper
#

ok… but the thing is that this is an additive process. I may do something (or not) independently of whether or not I should also do the rest of the process

little meadow
#

I see... 🤔

hard viper
#

TryDrawPreview false means it did not draw, but what if it did draw but needs me to go on as well

#

it’s partially a naming issue

#

i could make an out param, but idk if that exactly fixes the issue

little meadow
#

you could maybe return an enum instead of bool

#

then it's more explicit about the meaning of the value

hard viper
#
    out bool doNormalPreview) => doNormalPreview = false;```
#

maybe more recognizable?

little meadow
#

I'm not a big fan of out params... but it does seem like a reasonable approach

hard viper
#

i’m not either. this feels janky, but it is at least clear what I want to convey

sharp abyss
#

Hi guys, need some help. I'm trying to open a generic field to the inspector but I'm receiving an error:

"The field Dealer<System.Single>.affector has the [SerializeReference] attribute applied, but is of type Affector<System.Single>, which is a generic instance type. This is not supported. You must create a non-generic subclass of your generic instance type and use that as the field type instead."

The code it's pointing to is below:

public abstract class Dealer<T> : MonoBehaviour 
{
    // --- snip ---
>>> [SerializeReference] public Affector<T> affector;
    // --- snip ---
}

I'm concerned because the field's type is based on the class's defined type, so I cannot define a concrete type like the warning is suggesting. Am I SOL on this solution?

Unity version: LTS 2022.3.20f

little meadow
#

SerializeReference doesn't handle generic types

hard viper
#

yeah, just make a concrete type

little meadow
#

perhaps it's fixed in 2023 though

#

if you have the option to use that (I don't see this limitation mentioned in the docs there)

sharp abyss
#

I see, is there any other way to expose it it in the editor? if it helps the Affector<T> is a interface and I read this is one of the ways to expose it.

public interface Affector<T>
{
    //---snippy---
}
hard viper
#

I personally have:
FixedSpawnBase : Monobehaviour
FixedSpawnBase<T> : FixedSpawnBase
FixedSpawnSingle : FixedSpawnBase<TilePlacementInstance>
FixedSpawnLine : FixedSpawnBase<TilePlacementContiguous>...

little meadow
#

Odin Inspector

hard viper
#

but stop trying to serialize generics

simple egret
#

(consider prefixing interface names with I: IAffector<T>)

sharp abyss
sharp abyss
little meadow
#

so, you can't just use newer version of Unity?

hard viper
#

in general, if it is serialized, it should be a concrete type

little meadow
#

it is a concrete type, Unity is just kinda stupid 😛

#

(well, they seem to have fixed it in 2023, so there's that)

sharp abyss
hard viper
#

either way, you should get the tnrd serializable interface plugin

#

it is good for serializing fields that are an interface

little meadow
#

hey, you can use Pulni's Editor Tools if you wanna serialize interfaces and abstract classes and all that 😅

hard viper
#

unknown dev is sus

little meadow
#

but not the thing that you want, because technically it's still based on [SerializeReference]... it's more of a helper on top

sharp abyss
#

Gonna test the 2023 ver, o7 I'll give the tools a try later too. Thanks guys!

hard viper
little meadow
#

also uses [SerializeReference] inside so can't handle generics of that type, but seems pretty cool otherwise 👍

hard viper
#

I wouldn't expect it to handle generics tbh

little meadow
#

well it is just a Unity limitation 🤷‍♂️ ... nowadays you can do [SerializeField] private MyClass<int> myVar; and it'll show just fine... but if you wanna do SerializeReference and gain the ability to serialize interfaces/abstract stuff - it doesn't work

terse quarry
#

Im using this code to take a screen capture of a specific region

#

it captures from the smaller camera

#

it works fine in the editor, but when i build my project the screenshots it returns are blank with the wrong resolution

#

So im guessing the camera is scaling weirdly during building or something like that

#

1 is in editor, 2 is in build

#

I dont really know how to fix it because I dont know how building affects things like this

sharp abyss
little meadow
sharp abyss
#

Hehe you're welcome to give it a shot. Maybe you'll catch something 2am brain missed

#

This is what I currently have if it helps at all

Unity Version: 2023.2.12f1

Generic.cs

public abstract class Generic<T> : MonoBehaviour 
{
    [SerializeReference] public IInterface<T> affector;
}

public interface IInterface<T>
{
}

Concrete.cs

public class Concrete : Generic<float>
{
}

put Concrete on a Gameobject and the field will not be shown

hard viper
#

it makes sense for an enum that tells me the overall play mode to be a static variable, right?

#

eg. in overworld, in level, in main menu...

#

otherwise I think i'm struggling with singletons instancing in order or disappearing.

#

making it static fixes a lot of issues with initializing and closing, but i get an ominious feeling of doom

little meadow
#

I'd say go for it until it's a problem 😛

#

main issue I've had with static things is when you wanna do a clean reset, you need to tell all the static places to lose their data

hard viper
#

the main use case is to tell the main scene if we are in level editor mode or not. So clean reset isn't really a problem... probably

little meadow
#

This one specifically doesn't seem like it'll be problematic, yeah

nocturne wyvern
little meadow
#

(having a class Concrete : GenericTest<float> like you)

fringe scroll
#

I'm using the Spline Package so I can move things around in my scene along a path and I have looked at the documentation, but I can't seem to find what I'm looking for.

I would like to know the following

  1. Is there a way to tell if an object has fully completed a path over the Spline.?
  2. Is there a way to change the speed of an object while traveling over the spline?
  3. Is there a way to tell the object to stip following the Spline for a set period of time?
  4. If I want to have an object branch onto a linked Spline how do I tell the object if it should do so?
rocky jackal
#

how can i edit the post procesisng volume intensity with a script ?

simple egret
rocky jackal
simple egret
#

Ah no that's the weight of the volume component itself

#

That would be modifying its .weight property

rocky jackal
#

ahaha now that im using the right name i actually found it, thank you

random oak
#

is there a better way to do this?

 public void Method(int index)
    {
        index = (index + 1) % MyList.Count;
        if (index == 0)
        {
            WrapCount++;
        }
        var thing = MyList[index];
    }```
rain minnow
random oak
terse quarry
#

This doesn't count that though, does it? It just adds 1 to the WrapCount if it wraps at least once

#

Unless you're repeatedly calling it for each index

#

Oh hold on

steep herald
#

@random oak you could keep the raw index, use int div to know the wraps count and use modulo when accessing the list

random oak
steep herald
#

@random oak What 2 indices?

#

WrapCount can be determined dynamically by index / yourListCount

#

if you don't use modulo on your index

random oak
simple egret
#

With your current code, the index isn't kept. The one you pass is incremented and wrapped if needed, but that's pretty much it. You probably want to do it on a field instead, and modify the method so it doesn't take any parameters

young sage
#
itemSlots[col][row].(MainFrogController)Item.FrogController

Is there a way to cast Item to something and get a variable in the same line? Or do I really need to put the casted Item into a variable and then use the getters?

random oak
simple egret
#

Local variables are discarded when execution exits the method, and the fact that int is a value type, you're working on a copy, whatever variable you passed to the method won't be modified at all

simple egret
#

Note that this will throw an exception if the cast fails. If it's possible to have anything else than a MainFrogController in thata property, consider type-checking before casting it, or using is to both type-check and cast at once

#
var item = ...;
if (item is MainFrogController ctl)
  // use 'ctl' variable which is 'item' cast to 'MainFrogController'
hard viper
#

parentheses are always great

#

until you get into a dumbass twitter argument where people don’t remember how math works without them

#

one of the worst ones was most people saying
-1^2 = 1, which is just wrong

random oak
#

-(1^2) 🙂

little meadow
#

in all fairness, sometimes it's better to be explicit with the parentheses just so that people don't have to remember the order of operators and no random mistakes happen

latent latch
#

- ^ 1 2

little meadow
#

the -1^2 may confuse people, because ^ is somewhat uncommon to deal with

#

(and of course we're ignoring the fact that in C# that's a bitwise xor operator and not a pow operator 😄 and I have no idea what is its order relative to the unary - 😄 )

simple egret
#

If I remember correctly it's one of the lowest, below == so it's weird at first when you do a ^ b == 42 and it complains

heady iris
#

Unary operators beat all of the binary math and bitwise operations

whole garden
#

Hello everybody !
I'm currently making a shooting system and i have an issue, my bullet get out of my muzzle as wanted but it is shooting not at the center of the screen, i have my gun deported of my camera and i wan't to shot my bullet where the center of my camera is.

Do you know how could i improve this script ? :

            //direction from the weapon muzzle to the weaponpoint (where the player is aiming)
            Vector3 direction = (weaponPoint.transform.position - this.gameObject.GetComponentInChildren<WeaponParts>().weaponMuzzle.transform.position).normalized;
            bullet.GetComponent<Rigidbody>().AddForce(direction * weaponSpeedBalisitic);
            bullet.AddComponent<BulletScript>();```
fading girder
#

guys why can't I git push files over 100MB? I read online that github desktop has lfs and should be able to do that?

tame lynx
#

Hey, if somebody could help me with my FPS-Rotating that would be great.

This is my first time really programming a charactercontroller myself and not just copying a tutorial or using a free asset.
I wanted to do it myself.

    void CameraPositionSync()
    {

        Vector3 offset = head.forward * headZOffset;
        maincamera.position = head.position + offset;
        
    }

    void HandleLook()
    {
        //Rotate the player left and right based on the look input
        float XRotation = inputHandler.LookInput.x * lookSpeed;
        transform.Rotate(0, XRotation, 0);

        verticalLookRotation -= inputHandler.LookInput.y * lookSpeed;
        verticalLookRotation = Mathf.Clamp(verticalLookRotation, -UpDownRange, UpDownRange);
        maincamera.transform.localRotation = Quaternion.Euler(verticalLookRotation, 0, 0);
    }
#

I have some problems explaining what I am doing (as english is my second language 😅 Sorry)
So here is a small video of my FPS controller problems.

knotty sun
#

transform.Rotate(0, XRotation, 0) *;
???

tame lynx
#

Sorry, that musst have slipped in while copying the code 😅

oblique spoke
clever iron
#

I need help, I am coding a bow that just launches an arrow then you click but I cant get it to launch in the direction I am facing, but no matter where you turn it only launches in one direction, I have an arrow placeholder which is just a placeholder for the arrow to spawn at when instantiated and the arrow prefab. I am using AddForce to launch the arrow and I have it on Impuse. I used Vector3.forward for the direction but it is going forward globally rather than locally. Can anyone help?

#

Arrow placeholder code

#
using System.Collections.Generic;
using Unity.Collections;
using UnityEngine;

public class ArrowController : MonoBehaviour
{

    public GameObject arrowPrefab;
    public GameObject bow;
    public GameObject Holder;
    public GameObject player;


    public Vector3 startPos;

    public Quaternion startRot;


    public bool canLaunch;
   

    // Start is called before the first frame update
    void Start()
    {
        canLaunch = true;


    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (canLaunch) 
            {
                Launch();
                StartCoroutine(LaunchDelay());
            }
            
        }

        startPos = transform.position;
        startRot = player.transform.rotation;
    }


    IEnumerator LaunchDelay()
    {
        canLaunch = false;
        yield return new WaitForSeconds(1.5f);
        canLaunch = true;
    }


    public void Launch()
    {
        Instantiate(arrowPrefab, startPos, startRot);
    }
}
#

Arrow prefab code

#
using System.Collections.Generic;
using UnityEngine;

public class ArrowPrefab : MonoBehaviour
{
    public Rigidbody rb;

    public float shootPower;


    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.AddForce(Vector3.forward * Time.deltaTime * shootPower, ForceMode.Impulse);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnCollisionEnter(Collision collision)
    {
        rb.velocity = Vector3.zero;
        //Destroy(gameObject);
    }
}```
quaint reef
#

Otherwise same thing but reference the player, so player.transform.forward

clever iron
#

Oh wow thanks so much

quaint reef
#

Np

ashen jasper
#

Is there a way that the character can be seen though the wall depending on layer?

latent latch
#

camera tricks or rendering order tricks or stencil tricks

ashen jasper
#

I tired the camera trick though not sure why it never worked

ashen jasper
#

let me try that

weak venture
#

Hey not sure if the right channel but Im trying to grow a spriteshape over time. I have a script that basically does what I want with the exception of tangents. I set points to continuous tangent mode in the script but it doesn't seem to really take effect correctly.
If I go to the scene view and switch the point to linear, then back to continuous, it takes effect as I would expect. Is the missing step here that I need to calculate my own tangent points and set them in the script as well? Is there any way I can get the auto tangents the editor seems able to apply?

weak venture
#

I got a decent enough result using those tangent functions and just estimating good tangents based on a rough heuristic.

dim crypt
#

How was this hyperlink done?

simple egret
dim crypt
#

Thank you, works

dim umbra
#

is there a fixedUpdated version of getButtonDown?

dim umbra
#

need to know if a player presses a button while in a trigger collider but getButtonDown doesn't work

spring creek
#

You should never use single frame input in fixedupdate

dim umbra
#

what should I use instead?

spring creek
dim umbra
#

thanks

dense crow
#

have u guys use Physics.SphereCast with both index layermask and float maxdistance as parameter ?
they didnt work

#

it also happen to capsulecast

rigid island
dense crow
#
        float moveDistance = speed * Time.deltaTime;     
        bool hitted;
        Ray ray = new Ray(bottomPos, moveDir);
        if (useCapsuleCast){
            hitted = Physics.CapsuleCast(bottomPos, topPos, radius, moveDir, moveDistance, hitLayerIndex);
        }
        else{
            hitted = Physics.SphereCast(ray, radius, out RaycastHit hitInfo, moveDistance, hitLayerIndex);
        }
        if (hitted){
            Debug.Log("hitted");
        }
    }``` like this
rigid island
dense crow
#

layermask = index in editor + 1

mossy snow
#

bzzzt

dense crow
rigid island
dense crow
#

oh, so it is wrong knowledge

#

i read it somewhere

#

change to layermask worked

#

thanks a lot

spring creek
# dense crow layermask = index in editor + 1

That sounds like it's mixing this up with Random.Range (which you need to add 1 to for ints, because the int overload is max exclusive), and indexing in arrays (which you need to sometimes SUBTRACT one from, because array indexes start at 0)

In case you didn't look at those links, think of layermasks as just a series of flags, in a 32 option long list

sharp abyss
little meadow
#

Happy to halp! 😛

sudden ruin
#

help my first proj i been stuck on 2d map noise procedural generation with partial map loading
i cant find any yt guide for this, whats the approach to combine these two

robust whale
#

I can't make a fullbody fps controller with Unity 😦 can you suggest a tutorial for this?

soft shard
# robust whale I can't make a fullbody fps controller with Unity 😦 can you suggest a tutorial ...

What part are you struggling with, and what have you tried already? A fullbody FPS controller is just a regular FPS controller (so any tutorial on making a FPS controller should help), only adding a rigged model and aligning the camera to the head of that model, I would suggest making sure the model you use has the head separated from the rest of the body so the head can be disabled or set to a layer not rendered by the camera to avoid clipping

robust whale
#

Every time I try, I encounter a different problem and I guess there is no tutorial

soft shard
#

Sure, try that tutorial and see if it helps you, there should be tutorials on how to use the Rigging system package, though if you cant find anything on google, then describing your specific problem, setup, and desired goal can help, that video to me, looks like they may be using regular FPS arms and rendering a full body without the head and arms separately, or their animations are very well done, as posing, and aiming with a full body character can be difficult without the arms being a separate thing from my experience

icy depot
#

Is there some magic way to create a GameObject without having to reference copy another gameobject using Instantiate, but instead by simply creating an empty shell GameObject? The same kind you get when you create a new GameObject in hierarchy. I tried looking up "unity Instantiate without gameobject" but no luck...

#

I'm doing this because I find it a waste to go out of my way to get some empty prefab object's reference and instantiate like that, although i'll just resort to that method if needed

icy depot
#

I'll try that, thanks! new gameobject() seems weird to use..

knotty sun
#

why? GameObject is a C# class like any other

icy depot
#

that's really interesting, I didn't expect gameobjects to be so close

knotty sun
#

I suppose it's counter intuitive as you cannot use new() for Monobehaviours

icy depot
#

MonoBehaviour's an abstract sort of class right?

#

those types can't be created without an inheritor class, which makes sense

knotty sun
#

well, it's a bit more complicated than that because you cannot new() anything that inherits from MonoBehaviour either

icy depot
#

oh right, you can't really go new MyScript()

#

I wonder why

knotty sun
#

nope, only AddComponent

icy depot
#

maybe because the rest of the unity project has to know you added it? maybe the object it should be attached to for example

knotty sun
#

also Mono's span Managed and Unmanaged memory so there is a lot of stuff going on behind the scenes

icy depot
#

so the unity project has to manage the memory of the monobehaviour too

#

what sort of code prohibits newing a mono? maybe just explicit unity code?

knotty sun
#

exactly

icy depot
#

now that was interesting

lunar python
#

I have a problem with choosing the right animation. Currently, the from any state, we can choose to jump or walk, but using a bool for walking makes it overwrite the jump when player is jump and moving. Is there anyway to set priority for the animations? thanks

lunar python
#

nvm Imma create my own Animator Manager with Priority Queue for that

knotty sun
#

<@&502884371011731486> Spam

tawdry jasper
#

I have a super hard time working with unity's spline package. It doesn't seem to use any of the standard unity types (Vector3, Transform, etc) instead using Unity.Mathematics.math types. I'm sure this is useful with... burst? jobs? ecs? Is there some documentation primer on how to do it?
I used a third party spline package before (which was more "unity-y" in spirit), but would like to stick to the official one, is anyone using it?

Finally got GetBounds to work with trial and error, but ideally I'd want to do something like:

  • grab the spline from the splineContainer
  • get a new spline that's a copy of the original but with y=0
leaden ice
tawdry jasper
#

I'll have a look at the mathematics package docs, thanks. I know it must be a tradeof of ease of use vs performance, but I was expecting a spline will just be a list of points I would be able to loop through and alter or copy and all of that is probably possible but through some obscure SplineUtility helpers. 🤷

craggy veldt
long fox
#

I wanna make a VR game but I don't really have any coding experience. Should I learn general coding or lean how to code vr games straight off the bat?

#

What do you guys think is best

latent latch
#

You'd get hardstuck without knowing your coding.

long fox
latent latch
#

Absolutely, but you can dip your feet into Unity's tools and what templates they provide VR to keep you motivated.

heavy pecan
#

Does anyone have experience using GRFON? Im currently using it to try and handle getting translations for a project but i dont quite understand how to access a key/value pair within a collection.
The documentation has a lot of examples of creating grfon files and their layouts but theres only that one section for reading them in and actually using them so im a little lost.

long fox
latent latch
long fox
knotty sun
long fox
knotty sun
knotty sun
#

well first you need to make a financially successful game

knotty sun
long fox
mellow sigil
#

Thirdly after earning over a million dollars it would be quite petty to complain about having to pay for the software that made it possible for you to earn over a million dollars

long fox
knotty sun
long fox
knotty sun
long fox
knotty sun
#

would you prefer I lie and tell you you'll be a multi millionaire by the end of the month? And that game dev is really really easy

long fox
#

I mean thanks though

#

🙌

knotty sun
#

That is the 'talent' part I mentioned, if you have it you cannot not try

long fox
#

Thanks steve

gray mural
#

Hello. Let's say I have a NiceClass niceClass serialized in my script with [ExecuteAlways] attribute. How do I add a listener to it when it was assigned in the Inspector, making sure the listener is added just once and doesn't disappear when the script is reloaded?

#

I have a clue that the listener is added multiple times in OnEnable

grave tundra
grave tundra
#

I need something that can create closed shapes and test points

leaden ice
#

Yep

#

Splines is the package for you

#

if you mean testing if a point is inside the closed shape, use PolygonCollider2D.

grave tundra
#

Goal is to create a weird shape with a path, then create a depth map based on that shape to modify my mesh.

leaden ice
#

not sure what you mean by that, but you've now mentioned three sets of requirements that seem different

grave tundra
#

They're all the same. I want to generate a random shape that eventually I can use to deform my mesh.

leaden ice
#

You don't need a library for that

#

the mesh deformation part will be the much harder piece

#

you essentially want CSG

#

but the "generate a shape" part - as you mentioned and from the video is just using math to generate a sequence of points.

#

If you want to be able to sample the shape anywhere along its path - that would be wha the Spline package is for.

grave tundra
#

This is all runtime generation

leaden ice
#

so what?

#

That's why I linked you to realtime CSG.

grave tundra
#

Everything done from code.

leaden ice
#

naturally

grave tundra
#

I've already written the mesh deformation piece. That CSG tool isn't applicable for me.

leaden ice
#

Ok then use splines

#

for the shape part

#

as mentioned

grave tundra
#

thanks. haven't used them before so got a lot of reading to do to add a bunch of curves

lone echo
wide dock
#

Oh, you're setting it to kinematic in your script, but that also happens only if there is no Rigidbody2D present on your rocket. So here it's dynamic and affected by gravity.

lone echo
#

Brooooooooooooooo I kiss you

#

You are the best

light pond
#

How do i manage a componenet on the gameobject i just instantiated from the script

latent latch
#

you get back the ref from the component you instantiate

wide dock
latent latch
#

well, assumign you're not instantiating by the GO itself

light pond
#

i can maybe store it in a Variable?

wide dock
#

That's what variables are for

#

storing stuff in them

tardy crypt
#

Can anybody point me in the right direction for the following problem. I have a graph of nodes where all such nodes are connected to all other nodes through at least one path. I want to know when removal of one node creates two disconnected sub-graphs.

wide dock
stone rock
#

Hello, i need to have the vector that is perpendicular to the ground and was wondering if this is the correct way you would do this?

groundForward = new Vector2(hit.normal.y, -hit.normal.x);

I am mostly wondering if anyone knows the logic of when to use - or not for getting the surface aligned vector?

tardy crypt
#

I guess you don’t need the best route…

wide dock
#

I made something like not long ago, gimme a sec...

tardy crypt
#

I mean if you already know that a node to be removed is part of a connected graph, you only need to know if all its neighbors are still connected after removal right? So you don’t need to traverse all nodes?

vivid remnant
#

I made a procedural ladder. It is composed of two side rails and rungs that get added or deleted depending on the height I specify for the ladder.

#

When I try to decrease the ladder size, the rungs disappear.

#

Any idea why this could be happening?

#

The pieces that make up the ladder were created using ProBuilder.

proud fossil
#

In a card game if I have different types of cards if I have a common class "cards" but I want some cards to do something and others to perform other functions how should I develope it? I mean, I have a common class to all the creatures but they have subcategories
which perform different functions
In terms of code, any ideas of how should I face it?

proud fossil
#

srry

soft shard
tawny elkBOT
vivid remnant
vivid remnant
soft shard
#

Np, it happens

wide dock
vivid remnant
wide dock
# wide dock Yeah, that makes sense, if you're checking if others were also arrived after fin...
private int[] PathFill(Coords startingCoords)
{
    int[] pathMap = new int[NODES_COUNT];
    Array.Fill(pathMap, -1);
    int startingIndex = startingCoords.ToIndex();
    pathMap[startingIndex] = startingIndex;

    Queue<Coords> coordsQueue = new Queue<Coords>();
    coordsQueue.Enqueue(startingCoords);
    do
    {
        Coords checkedCoords = coordsQueue.Dequeue();
        int checkedIndex = checkedCoords.ToIndex();
        Coords[] connectedCoords = m_nodes[checkedIndex].GetConnectedCoords();
        foreach (Coords coords in connectedCoords)
        {
            int connectedIndex = coords.ToIndex();
            if (pathMap[connectedIndex] != -1) { continue; }
            
            pathMap[connectedIndex] = checkedIndex;
            coordsQueue.Enqueue(coords);
        }
    } while (coordsQueue.Count > 0);

    return pathMap;
}

Probably not the best solution in the world, but it works, didn't try it out for larger graphs tho (used it only for a max 21x21 board game). Could be modified to include a counter of checked nodes count, which can be later compared to some all nodes count to see if there were any nodes which were not reached. That, or just as you said, checking connections between neighbours of the node to be removed

lone echo
#

🙂

#

If I set the rigidbody to Kinematic, everything works great. Initially it is set to false, and upon collision with a meteorite it is set to true, resulting in the destruction of the rocket. The problem now is that the limit no longer works because there is no rigid body that behaves as if it were dynamic. However, when I choose a dynamic rigid body, even if the gravity scale is adjusted, all the parts start to fall, or it happens that the parts do not move together. Here are all the scripts and a video.
https://gdl.space/utalucucuy.cs PlayerScript (Rocket)
https://gdl.space/xafuwozure.cs BoundaryScript
https://gdl.space/vojajuvoge.cs Rockpart (Wings,Body,Engine,Arrow have that script)

https://www.youtube.com/watch?v=jvGmYJef-Sw

clever iron
#

Hmm that's interesting because kinematic usually makes it not work

lone echo
#

Yes, it's the boundary script that actually just makes a Box2D game object invisible and it needs the rigid body features, but the kinematics disables many rigid body properties and that's why the boundary script no longer recognizes my player because my player comes from an empty one Game Object has no real collider, and then when kids see the video history, they all have a rigudbody and a polygon collider, and in the playscript it was written so that the kids are the hitbox of the empty game object, but when I put the kids on in a filmic place then nothing works

#

but I still can't come up with a solution

somber apex
#

Hey all I'm currently attempting to make an x-com like project. I have pathfinding and the like working for multiple floors, however I'm a bit stuck with props. For example, each node in my graph structure can potentially contain a character, which is fine, however what if I have a prop on the node like a box? I want to be able to get a character to jump on the box or be able to move it, destroy it etc. Would anyone have an idea as to how this could be done/what sort of data structure would be best? Right now my box is just sort of sitting in the way haha

#

I'm currently thinking that I can add a node to the top of the box at runtime and from there the node on the box can work out what neighbours it has

tardy crypt
#

How about just an array of NodeContents objects, where NodeContents defines what is in it and their relationship?

#

You could probably define the pathfinding distance from one node to another node based on their contents.

#

As well as whether there is connectivity.

somber apex
#

I was considering that too; having an array of items within a cell contents, although I'm not entirely certain how I would establish the relationship in the first place. Maybe I can get the cell to just raycast up until it hits a roof or the sky and say everything that's not those is linked up

tardy crypt
#

Yeah I guess it’s dependent on your level editor or however you generate levels. You could have the relationship be the “ground truth” of your model and place objects based on that relationship rather than placing objects first and detecting relationship based on placement…

#

So like just start with “box at 63,10” and the engine will generate and place the box that way…

somber apex
#

Yeah I could try that out too. Thanks for the information; I'll see what I can sort out

fallow obsidian
#

why do i get this error when i drag in a script from my custom package into unity?
It says there's some compile errors but im not sure how to debug this since the script name and class name in script is same so that's not the issue. Hmm

trim schooner
#

The error doesn't say there ARE compile errors, it says CHECK FOR. However, your console shows there are no compile errors

charred ruin
lone echo
#

@charred ruin i try it wait

charred ruin
#

You might need to do the same for Polygon Collider and I noticed you have a custom script attached. Not sure what's in it but that might have to go at the parent level too.

lone echo
#

new video

#

When I remove the Ridigbody, the parts no longer fly through the air

static horizon
#

Within Unity C#'s framework, is there a property where I can assign a new layer to the gameobject?

light pond
#

when i import my pixel art and make it point no filter it messes up its pixels

wide dock
#

That ain't code

#

And we can only assume what you mean by "messes up its pixels"

light pond
#

oh wrong channel bruh

grave tundra
#

Anyone use DreamTeck Splines? I can't get RebuildImmediate to work without waiting a frame.

grave tundra
spiral oyster
#

can anyone tell me how to make this coroutine loop properly

#

its on an enemy that dashes towards the player and then waits a couple of seconds then does it again

naive swallow
spiral oyster
#

oh shit i forgot to remove that

#

i got rid of that I was just spitballing atp

#

ignore the && true its just time < seconds

#

it already does basically what I need it to do, but i need it to keep happening. I know how to use waitforseconds but I'm not sure how to in this context

naive swallow
#

Could just wrap it in another loop that has a wait in it for however long you want between runs

spiral oyster
#

I still would need the time, start, and pos variables updated

cobalt elm
#

                float steeringVel = Vector3.Dot(sp.right, worldVel);
                //Debug.Log(Mathf.Abs(steeringVel));

                if (Mathf.Abs(steeringVel) >= driftSensitivity) steerGripC = steerDriftGrip;
                else steerGripC = steerGrip;

                float velChange = -steeringVel * steerGripC;
                float accel = velChange / Time.fixedDeltaTime;

Rigth here I am working with a custom car controller. I have it pretty much all down besides drifting. My current idea is to check the lateral velocity and if it exceeds a threshold. It works fine but the physics do not. Usually when I lower the tire grip it slides/drifts like normal. But when I do this from high grip to low grip it will end up doing a weak ass turn with what seems like full grip. Any ideas? Thank you

#

this accel is applied here rb.AddForceAtPosition(sp.right * tireMass * accel + sp.up * force /*+ sp.forward * torque*/, sp.position);

quartz folio
# spiral oyster

Also note that Unity's Lerp is clamped, you don't need to clamp the t value yourself

crystal dagger
#

hey so

#

When I add a gameobject to another gameobject

#

For some reason the first one's position on the editor gets assigned to the child's position

#

why?

#

before and after adding the sword to the empty gameobject's

vapid bluff
#

Hello. I want to add a persistent lives and score canvas into my project. The problem I have now is that for some reason, when I die for the first time, the countdown for lives dissappear at 2, but when I die again, the countdown is shown again at 1. What should I do?

Edit: it was the font's problem

nocturne wyvern
#

Hi. why my EventSystem.current is null when I click with this clickable view?

public class ClickableView : View, IPointerDownHandler, IPointerUpHandler, IPointerClickHandler, 
        IClickableView
rigid island
nocturne wyvern
rigid island
cosmic rain
nocturne wyvern
#

So, my mistake, current is not null, but currentSelectedGameObject is null

gray thunder
#

ur not working with a gameObject but with UI

earnest gazelle
#

I prefer string collection instead of enums for this situation, what do you think?
I want to implement a generic class with different enums. I can use the generic one with T: Enum but if it is string, it would be so easy to handle it, it is more flexible. Another scenario is animation name/type.
What do you think?
Using enums has some limitations while string does not

// enum implementation
_animationController.Play(CharacterAnimations.Shoot)
_animationController.Play(AnimalAnimations.Eat)
public class AnimationController<T> where T:Enum{}
crystal dagger
#

So, I made the cape cloth, and since i didn't know how to make those dangling thingies, to be dangled and with physics, so i made them cloth too (so you can already see it's not working as intended since it'll deform, and it's meant to be straight)

#

does anyone know what component do i have to use?

spring basin
#

got this piece of code, off chatgpt
it seems to be working fine pointA and pointB share the same y position

#

how do i make it add a y offset perpendicular to the direction between pointA and pointB?

distant wadi
#

Posted this in mobile channel but that is very much a non active chat these days. I have a really annoying issue with the simulator resizing itself and scaling itself incorrectly when the window is resized (2022.3.X). Anyone know any fixes and / or work arounds that dont involve just randomly jiggling the window until it fixes itself?

rancid frost
#

How do u guys serialize your data?

#

JsonUtility can be serverely limiting

thick terrace
leaden ice
knotty sun
little meadow
rancid frost
#

I see

neon plank
#

Question, how can I make the animator to call the OnStateExit methods of its StateMachineBehaviours when the gameobject which contains the animator is disabled?

rancid frost
#

there are events for such things

#

u can set them in editor, look it up

neon plank
# rancid frost https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html

But I'm using state machine behaviours instead, which support write custom code which is then executed in callbacks.
Also, I'm quite sure that animation events also don't get called if the animator is disabled (they already don't get called if the state is transitioned from before it exits, unlike OnStateExit which does)

rancid frost
#

ahh I see

rancid frost
#

How do you guy save non monobehavior classes that are instantiated?
specifically classes that use unity objects such as textures materials etc

rain minnow
rancid frost
#

I have created a main scriptableobject which contains all the textures to be used and creates a unique ID for said textures...
then I simply serialize the ids.

However, said instances are instances of an INTERFACE...so JsonUtility cannot be used

Yes, its runtime

cosmic rain
#

You can override the serialization logic of the JsonUtility for the desired objects.

#

If you generate new textures and want to save them, you'll need to save them as PNG or something similar probably. As for materials, create a custom class to serialize and recreate a new material from it on loading.

rancid frost
#

Im not generate new mats or textures

cosmic rain
#

Then just save the IDs

rancid frost
#

How would I know the type before deserialization/

cosmic rain
#

serialize the type as well

#

If it's really needed. Because if you override the serialization, you should have control over what and how you serialize/deserialize.

rancid frost
#

where can i find more info on the override? cant see on internet

neon plank
#

Anyway, OnDisable seems to work in this behaviours

heady iris
#

Yeah, use OnDisable.

#

OnStateExit is called when you exit the state (and only when you exit the state)

neon plank
heady iris
cold minnow
#

Does anyone have a good resource for limiting framerate without disabling vsync? I'm handling it like this right now for end users but I really would like to not have to disable vsync if it's possible. Trying to find good info online on this topic is like trying to bleed a stone 😅

cold minnow
# latent latch project settings you can limit frame rate

I appreciate the time. Yeah this is all I'm able to find on the matter, but this either requires disabling Vsync or using arbitrary values based on screen refresh rates. I'm looking for ways to limit to 30 or 60fps regardless of the screen refresh and without disabling vsync 🤔 Such a pain that this isn't more simple to do

heady iris
#

Application.targetFrameRate is all you need

#

it limits the framerate

robust whale
#

I move my character's arm with the help of a target. this target moves with raycast, but this method does not work when it does not touch a different object. How can I do it with a method?

Ray ray = new Ray(transform.position, transform.forward);
if (Physics.Raycast(ray, out RaycastHit hit)) {
  aimTarget.position = Vector3.Lerp(aimTarget.position, hit.point, 10f * Time.deltaTime);
}
#

try this;

            float lookX = playerInput.lookX * mouseSensivity * Time.deltaTime;
            float lookY = playerInput.lookY * mouseSensivity * Time.deltaTime;

            transform.position = cameraRoot.position;

            xRotation -= lookY;
            xRotation = Mathf.Clamp(xRotation, -90f, 90f);

            transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
            playerBody.Rotate(Vector3.up * lookX);
leaden ice
#

or you can use the same Lerp thing you have currently just use ray.GetPoint(100) in place of hit.point

robust whale
tall birch
robust whale
robust whale
# leaden ice show code
            Ray ray = new Ray(transform.position, transform.forward);
            if (Physics.Raycast(ray, out RaycastHit hit)) {
                aimTarget.position = Vector3.Lerp(aimTarget.position, hit.point, 10f * Time.deltaTime);
            }
            else {
                aimTarget.position = Vector3.Lerp(aimTarget.position, ray.GetPoint(100), 10f * Time.deltaTime);
            }
leaden ice
#

well how far is the thing you're hittin when you switch over to not hitting anything?

#

It looks like your raycast distance is unlimited right?

#

try a further distance like 1000 and see if that's any smoother

tall birch
tall birch
#

whole character started floating

#

nvm I fixed it

#

thanks

stuck forum
#

Bump

robust whale
robust whale
leaden ice
latent latch
#

Any alternatives to ZipFile.ExtractToDirectory for unity that I can yield from using coroutines? Using webgl and apparently I can't use async operations.

#

so my options right now looking at, chop the zip into little bits, or let the main thread freeze for 10

leaden ice
latent latch
#

oh no js

#

x__x

#

I guess that's what it's looking like. Itch.io requires a lot more internal zipping as it'll not accept all of it in your streaming assets.

elfin tree
#

Anyone has or know where to find a code snippet of a rigidbody following a transform using .AddForce(), seems like there's a few things that would go into doing this and I can't quite wrap my head around it.

leaden ice
#

are you trying to make it intercept the target?

#

Or keep a specific distance or offset?

#

or what

#

It's a second level derivative problem because:

  • What you want to change is position
  • What addforce directly changes is actually velocity, which later changes position over time
elfin tree
#

I'm thinking about having multiple entities following each other making a compeling line, so the 'leader' just goes at a set speed and be non physic based, could implement some wait if it's too far away or whatever

each individual has a set max speed, so no offset, it just tries it's best to keep up
i can do that fine using MovePosition but it defeats the purpose

leaden ice
#

The basic idea though is you figure out the desired velocity you need (based on position and direction to the target), compare that with your current velocity, then apply a force to correct that discrepancy

#

Like for example, in FixedUpdate

Vector3 targetPos = target.position;
Vector3 currentPos = rb.position;
Vector3 direction = targetPos - currentPos;
Vector3 desiredVelocity = direction.normalized * maxSpeed;

Vector3 currentVelocity = rb.velocity;
Vector3 desiredVelocityChange = desiredVelocity - currentVelocity;

// The most we could change velocity given our max available thrust force.
Vector3 bestVelocityChange = Time.fixedDeltaTime / rb.mass * maxThrustForce * desiredVelocityChange.normalized;

Vector3 actualVelocityChange = Vector3.ClampMagnitude(bestVelocityChange, desiredVelocityChange.magnitude); // don't change more than needed

rb.AddForce(actualVelocityChange, ForceMode.VelocityChange);```
I used ForceMode.VelocityChange here but factored in deltaTime and mass manually so it's effectively a normal AddForce.
#

I made this very verbose too, to try to make it easier to read/understand

elfin tree
#

oh wow tysm

#

will tinker with that for a bit

tawny elm
#

for some reason the videoplayer components just dont stop with this

        videos = GameObject.FindGameObjectsWithTag("Video");
        foreach (GameObject video in videos)
        {video.GetComponent<VideoPlayer>().enabled = false;}```
#

i also tried Stop() beforehand but that did nothing

leaden ice
tawny elm
#

it just doenst stop the videoplayers

robust whale
leaden ice
#

you need to do some debugging

tawny elm
thick terrace
leaden ice
tawny elm
leaden ice
#

no

#

it wasn;'t

#

it was

#

take concrete debugging steps like adding log statements

#

You seemingly have not done so yet.

tawny elm
#

log statements have one come up for each of the loaded videos

#

so its definitely finding them

leaden ice
#

I don't see any logs in your code

tawny elm
#

just doesnt stop anything

#

yeah well i didn thave them in there when i did that because i was changing it around a lot

rancid frost
#

Well boyz, I did it!,

I finally serialized my custom class...only took me 1 week 🙂

leaden ice
#

otherwise we will waste time following down the wrong path

tawny elm
#

well how about lets get to what im meant to do now

leaden ice
#

So you have verified that your objects are actually being found?

tawny elm
#

yes

#

i said so

leaden ice
#

not until just now

#

if so, calling Stop() on them should stop them

tawny elm
#

i already said that doesnt stop them

leaden ice
#

Then perhaps you're calling it on the wrong objects, or perhaps you have some other code restarting them

#

or maybe you have some errors happening

tawny elm
#

theres no errors

#

i already said that one

leaden ice
#

When and where is this code running

#

and when and where do the videos start playing

#

Share some screenshots of how this scene is set up and where these objects are and which script is doing this and when?

unique delta
#

How can i check if a button is selected?

tawny elm
# leaden ice When and where is this code running

that code i shown is in the gamemanager
the part that plays the video is in here
the videoplayer is displayed on an object called fullscreenvideo
the videoplayer component is inside the button that these events are on
closevideo is just the button that activates the code in gamemanager i shown

leaden ice
#

Can I ask why you directly reference the object for the play button but the stop button calls this code that finds it by tag?

#

Just curious

tawny elm
#

i tried just directly referencing each before but that didnt work and is why im at finding by tag now

#

i did that bit yesterday so i forgot about it

pseudo beacon
#

hey sir !

tawny elm
#

i just tried having the play vidoe button do its stuff in the gamemanager too even though it shouldnt really do much (?) but its at least a bit neater

#

didnt change anything

unique delta
tawny elm
unique delta
#

is it even posible?

tawny elm
rigid island
unique delta
#

it dosen t work

rigid island
unique delta
#

no i got it i m dumb

#

i just had to implement the

rigid island
#

method

#

yes

unique delta
#

yes

thin aurora
tawny elkBOT
tawny elm
#

i already tried it

#

it doesnt work

#

on my computer at least

thin aurora
#

It's for your own good to have it configured, and very often an issue is resolved this way anyway

tawny elm
#

what exactly is the benefit

#

i managed to get it configured at one point but it went away when i restarted my pc

#

i didnt see what the fuss was about

primal wind
#

It makes troubleshooting a lot easier

#

And makes coding a lot less painful

little meadow
#

auto-complete, telling you about frogloads of errors before you even think of doing something... debugger

rigid island
#

other than a TextEditor

tawny elm
#

it already has auto complete though

thin aurora
tawny elm
#

and syntax highlighting

#

im think

rigid island
#

like this ?

thin aurora
#

Not in that picture

tawny elm
rigid island
#

if it shows Unity components n such then you're good

primal wind
#

Wonder how awful the DX would be if the code was fully white

tawny elm
#

if its that easy to spot idk whats going on rn

rigid island
#

maybe the color theme threw them off

thin aurora
#

The different related keywords would be colored correctly

#

That's enough reason to believe it's not configured, when that does not work

primal wind
#

Is it VSCode?

tawny elm
#

its vscode

spring creek
primal wind
#

Depends on the theme

rigid island
#

(using test code line obv)

spring creek
rigid island
#

if you dont have the light bulb though you're def not configured

primal wind
rigid island
#

types default is Green

#

the thing I dont like about default theme in VSCode is the light blue for member variables..
In Visual Studio they are default white/gray, blueish is color for local variables

faint nimbus
#

I tried checking if this works in my interactor script, i declared testing as public Vector3 testing = new Vector3(40, 0, 0); and hooked it to the click thingy and it worked if (Input.GetKeyDown(KeyCode.Mouse0)) { interactable.onInteract.Invoke(); Debug.Log("Toggled"); // Apply the rotation interactable.transform.Rotate(testing); but now that I know I could put variable thingy inside the transform brackets, I do not know how to link this thing to the transform command earlier ```
public Dictionary<int, Vector3> rotationDictionary = new Dictionary<int, Vector3>();

void Start()
{
    rotationDictionary.Add(1, new Vector3(-30, 0, 0));
    rotationDictionary.Add(2, new Vector3(20, 0, 0));
    rotationDictionary.Add(3, new Vector3(0, -10, 0));
}``` I assigned int in my interactable script so that I could link it to my interactable's itemID, but dont know how it would interact inside the interactor script, or how would he dctionary reference the itemID to the int inside the dictionary
rigid island
faint nimbus
#

I am not good with words, if ok UnityChanDown

rigid island
#

its fine, just need to know more or less the game mechanic

#

or what you want it to do

faint nimbus
#

I want to connect itemIDs int from interactable to interactor's dictionary, but dont know how, and I want to connect dictionary to interactable.transform.Rotate(dictionary maybe);

#

it is like, there are cars, carpets and brooms in the scene, i want cars to rotate rotationDictionary.Add(1, new Vector3(-30, 0, 0)); and carpets to rotate as rotationDictionary.Add(2, new Vector3(20, 0, 0)); and brooms to rotate as rotationDictionary.Add(3, new Vector3(0, -10, 0));

#

it happens on click

#

and I want to assign if they are 1,2, or 3 (itemID inside interactable) to know if they are cars, carpets or brooms

#

and I used dictionary to store how they would rotate

#

but dont know how to link them together UnityChanDown

#

I could assign 2 to a car (using interactable's itemID) and it would rotate like how a carpet would rotate etc (using dictionary)

#

but i dont know how to make them work together

#

is ok? or confusing UnityChanThink

rigid island
faint nimbus
rigid island
#

oh so do you have reference/access to the script ?

faint nimbus
#

hmm, it is like, I dont know how the value of interactable's itemID relate to interactor's dictionary to change the interactable's position

rigid island
#

I dont even know what these itemIDs are for , why not use enums

#

make it more explicit whats wat

#

I still don't get the

I could assign 2 to a car (using interactable's itemID) and it would rotate like how a carpet would rotate etc (using dictionary)

#

so you want the rotations to be inside the dictionary and then you pullup the rotation stored?

faint nimbus
#

i plan to match it with interactor's dictionary of 1,2 and 3

#

but dont know how they can meet or work together

#

so that interactable can use dictionary's x y and z

faint nimbus
rigid island
#

myRotation = Quaternion.Euler(rotationDictionary[id])

faint nimbus
#

ah, is it inside interactor?

rigid island
faint nimbus
#

interactable.transform.Rotate(xyz); this is the code that makes it rotate when clicked

rigid island
#

or use transform.Rotate(rotationDictionary[id])

#

right

faint nimbus
#

can I use Transform.Rotate(rotationDictionary[itemID])?

rigid island
faint nimbus
#

but it is in interactable, would it find it?

rigid island
#

that is how you access your V3 values

rigid island
faint nimbus
#

ah, how do we reference other scripts?

#

is like this? public Interactable interactable;

rigid island
#

exactly thats a reference

#

you just need to assign it

faint nimbus
#

ah it makes sense noww

#

I think I know how to get from other scripts now, I will try

rigid island
#

sure thing! lmk if you have any issues

faint nimbus
#

okok UnityChanOkay

#

hmm, why wont it find it? interactable.transform.Rotate(rotationDictionary[itemID]); in interactable, I have public int itemID

leaden ice
faint nimbus
faint nimbus
#

but i need transform thingy

heady iris
#

itemID is an integer

#

you can't invoke an integer

#

this syntax is very wrong

#

you're trying to use the indexer operator on rotationDictionary with no parameter, which is invalid

faint nimbus
#

sorry, I dont know UnityChanDown I'm trying

heady iris
#

don't just randomly mash syntax together

#

think about each step individually

#

first, you need to get the item ID

#

where does the item ID come from?

faint nimbus
#

ah

#

interactable.transform.Rotate(rotationDictionary[interactable.itemID]);

#

is ok?

heady iris
#

That looks reasonable, yes.

#

You get itemID from interactable and use that to index rotationDictionary

#

then you pass the result to Rotate

faint nimbus
#

I thought the way parenthesis work, it would try and get something from it, and put it inside the [], i got confused

#

i will try

#

it worked UnityChanOkay

#

thank you navarone, Praetor, Fen

#

I'm a bit slow, hope it is okUnityChanSalute

rigid island
#

no worries gotta start at slow pace, eventually it will pick up if you keep at it

dusky pelican
#

Hello, i use a lot of LocalizationSettings.StringDatabase.GetLocalizedString in my scripts for directly get the translation of the string. Is it bad practice?

knotty sun
dusky pelican
rotund moat
distant oyster
#

how to get end position of raycast which is not hit with anything and it has length

leaden ice
leaden ice
#

if you don't actually have a Ray then it'd be rayStartPos + direction.normalized * length

rotund moat
leaden ice
#

that's not going to actually move objects with the physics engine

rotund moat
#

in game it works same

leaden ice
#

how are you moving the objects?

#

I would bet you're teleporting them via the Transform

rotund moat
#

like when the player falls from a great height he flies through colliders

knotty sun
leaden ice
spring creek
#

And make sure you move with the rigidbody, not the transform, unless you want to HAVE to do physics queries to prevent clipping

scarlet viper
#

i build a game with 120fps cap and use this code (or any other rotating code)

void Update()
{
  transform.Rotate(0f, 10f * Time.deltaTime, 0f);
}```
and it warps sometimes? Im rotating a camera and the scenery is basically a few long pillars and as the camera is moving theyre mostly passing through screen smoothly but sometimes they warp. i for sure have 120fps so im unsure whats wrong
#

it cant really be seen on video (on video they always warp bcuz recording took some FPS probably)

leaden ice
#

especially if this is in the editor, you will often experience intermittent chugs

#

Are you sure you're not just seeing a framerate hitch?

scarlet viper
#

its in build

leaden ice
#

builds can have framerate hitches too

#

attach a profiler and see what's going on

scarlet viper
#

hyeah that was just VSync capped at 120fps. it works fine at 60fps cap

#

seems 120fps was too much

latent latch
#
TextAsset text = bundleRef.LoadAsset<TextAsset>("assets/bundles/substrings/" + substring + "_.bytes");

So to load from an asset bundle, even though we need to specify the reference to the bundle, we still need the FULL path to the asset and not the path relative to the bundle?

latent latch
#

or rather it snapshots the directory it's built in and you have to navigate that

#

maybe it's just this asset bundle tool

grave tundra
#

If I have two closed polygons defined by splines, is it possible to generate a new spline that is the union of the two to create a single polygon? (Currently using Dreamteck)

sour latch
#

Help, how do i make an object that is rotating flip when turns 180 degrees?

light knot
#

Hey, sorry it's half a month late, I usually don't check Discord, but I'm the lead eng on Muse Behavior, feel free to tag me in questions, or message on the Unity Discussion pages for Muse which I'm quite active in 🙂

barren wasp
#

ok, wait, do i have to cast a raycast to know if there is a wall, then make it so the player jumps to the opposite side with 1.5x the jump power to make a wall jump?

light knot
#

This is just for an easy demonstration and not serious development, but yes, find at runtime is no good 🙂

#

For the original question: Did you assign a blackboard variable to the node and did you assign a value to your variable in the inspector for the gameobject?

wicked river
# light knot For the original question: Did you assign a blackboard variable to the node and ...

Hey, I got quite far and I am actually stuck on much more complicated issues then initially .

The main issue I am facing is switching to the right state at the right time and ensuring the npc does what it needs to. I have been really active is the unity Discussion . You can find the full thread here - https://discussions.unity.com/t/muse-behaviour-getting-started-issues/338435/35

rigid island
light knot
#

I hope the information from Trevor helps otherwise. Did you try with his fix?

wicked river
#

Completely lost to be very honest

light knot
#

Well, if you want to have a chat sometime let me know and I'll see if I can help 🙂

wicked river
light knot
#

Yeah, feel free to, or continue the discussion on the discussions pages so Trevor can also join in, whichever you feel like.

#

Happy to jump on a zoom call if needed to look into what's going on

#

Just a note I'm based in the UK so will need to figure out the timezones (don't ask me why I'm responding at 23:42! I care about the project quite a bit 😅 )

spring creek
barren wasp
spring creek
#

Perhaps OverlapSphere is more what you're looking for?

#

Or simply attach a sphere collider and add OnTriggerEnter to your code?

lean sail
#

I have an enum in a base class of a SO, EffectType is the enum

public abstract class EffectSO : ScriptableObject
{
    public EffectType EffectType => effectType;
    [SerializeField] protected EffectType effectType;
}

In a specific child class I want to enforce effectType to only be a specific value but I am having problems. I tried setting the value in OnEnable and OnValidate but it seems to go back to the default value after I rename the SO (see video). OnValidate does set it to the correct value properly after i change something but its awkward to do. Id like it to be set right away. I am probably missing something stupid.
What can i do to fix this?

barren wasp
#

i presume, when collider enter return something so it can wall jump

#

this on the collider

spring creek
barren wasp
#

oooohohhhhhhhhhh, thx

latent latch
#

need to probably add flags though so it sets once

modern creek
#

I'm having some weird issues with the android resolver while trying to .. resolve. I've just downloaded and installed the ironsource levelplay package and ... the android resolver seems to be having issues with it:

Win32Exception: ApplicationName='D:\projects\unity\2048CE\Temp\PlayServicesResolverGradle\gradlew.bat', CommandLine='--no-daemon -b "D:\projects\unity\2048CE\Temp\PlayServicesResolverGradle\PlayServicesResolver.scripts.download_artifacts.gradle" "-PANDROID_HOME=D:/Program Files/Unity/2022.3.17f1/Editor/Data/PlaybackEngines/AndroidPlayer\SDK" "-PTARGET_DIR=D:\projects\unity\2048CE\Assets\Plugins\Android" "-PMAVEN_REPOS=https://android-sdk.is.com/;https://maven.google.com/" "-PPACKAGES_TO_COPY=com.ironsource.sdk:mediationsdk:7.8.1;com.google.android.gms:play-services-ads-identifier:18.0.1;com.google.android.gms:play-services-basement:18.1.0" "-PUSE_JETIFIER=1" "-PDATA_BINDING_VERSION=7.1.2"', CurrentDirectory='D:\projects\unity\2048CE\Temp\PlayServicesResolverGradle', Native error= The system cannot find the file specified.

I can't tell what file isn't found - the SDK appears to be there, although the / is backward on the last part of the dir.. Not really sure what else to look for. Since I've installed the LevelPlay plugin - any android build just hangs, and tailing the editor.log shows it farts on that stack trace then just hangs (45 minutes before I killed the process entirely)

native folio
#
        if (joinButton.onClick.GetPersistentEventCount() == 0)
        {
            Debug.Log("we can add click, this is first time!");
            joinButton.onClick.AddListener(() =>
            {
                MainMenu.instance.Join();
            });
        }```
why does the debug statement keep printing even after ive added the listener?
#

this function gets called multiple times btw

modern creek
#

add listener doesn't add a persistent listener, but GetPersistentEventCount() gets the persistent listener count

native folio
#

what's the difference between persistent and regular listener?

modern creek
#

I don't know exactly but I imagine it's a listener that's serialized in the inspector

native folio
#

Ah

modern creek
#

In any case, you can give your listener an actual method, then just add/remove it normally (which you probably should do) in onenable and ondisable

#
private void OnEnable()
{
  joinButton.onClick.AddListener(ClickHandler);
}
private void OnDisable()
{
  joinButton.onClick.RemoveListener(ClickHandler);
}
private void ClickHandler() { ... }
lean sail
dry kayak
#

You ever zone out so unbelievably hard that you start doing "is not less than" operators.

#

Hit em with the
!<

faint nimbus
#
    {
        rotationDictionary.Add(1, (new Vector3(-60, 0, 0), new Vector3(60, 0, 0))); // Example values for item type 1
        rotationDictionary.Add(2, (new Vector3(20, 0, 0), new Vector3(0, 0, 0))); // Example values for item type 2
        rotationDictionary.Add(3, (new Vector3(0, -10, 0), new Vector3(0, 0, 0))); // Example values for item type 3
    }``` how do I set this up to make it not add or subtract it everytime it happens (to prevent bugs of it overflipping), instead, set it to that vector? like if I click it when on, it will be on that position no matter how many times i click it
#

is it because it is .add which is why it adds the vector?

#

can it be .set? i am not sure what to put

wicked scroll
#

man that's not a very useful tutorial

wet wadi
#

Hi, I have game events that get activated when the player goes through a collider trigger, and the game events follow a path by the waypoint system. But my problem is that they all activate at the start of the game prematurely. How do I fix this? I don't know what's causing this. The code is below: ```

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

public class IncomingCar : MonoBehaviour
{
[SerializeField] private GameObject pedestrian = null;
// Start is called before the first frame update
void Start()
{
pedestrian.SetActive(false);
}

// Update is called once per frame
void Update()
{

}

private void OnTriggerEnter(Collider Other)
{
    if (Other.CompareTag("Player"))
    {
        pedestrian.SetActive(true);
    }
}

}```

spring creek
wet wadi
#

oh wait

#

sorry misunderstood ur question

wet wadi
#

yeah pedestrian is the event thing that follows the waypoint

spring creek
# wet wadi yeah pedestrian is the event thing that follows the waypoint

Ok, then the issue is probably that pedestrian starts awake. You can set it to disabled in the inspector before runtime so it STARTS disabled.
Start runs after Awake and OnEnable.
Not sure how pedestrian is supposed to work, but if stuff happens in OnEnable, then disabling it in start is too late

wet wadi
spring creek
#

SetActive can't be moved to the inspector

#

Or just use ACTUAL events, which are called in OnTriggerEnter

wet wadi
spring creek
#

One sec

wet wadi
#

oh okay yeah the place i work at calls it "events" cause my boss ain't a unity person

#

i'll look at that too

#

the fix seems to work

#

thanks

spring creek
#

And they exist in many programming languages too

wet wadi
#

my boss isn't a coder person either

frosty widget
#

I have a question about coroutines: between these two yield statements, would this segment of code be executed every frame or would it just be executed once?

somber nacelle
#

unless you have a loop or start multiple instances of the coroutine then that code executes only once

frosty widget
#

ok thank you

#

any suggestions on how I would make that segment of code loop over a certain time period?

sullen drift
#

genuine question, do i have to unsubscribe my event when using UnityEvent?

cosmic rain
sullen drift
#

what if i assign it through only inspector, not script?

#

do i still need to unsubscribe?

spring creek
faint nimbus
cosmic rain
orchid abyss
cosmic rain
faint nimbus
cosmic rain
spring creek
cosmic rain
faint nimbus
#
            {
                interactable.onInteract.Invoke();
                Debug.Log("Toggled");
                ///interactable.isOn = !interactable.isOn;
                // Get the rotation settings based on item type
                (Vector3 onRotation, Vector3 offRotation) rotationSettings = rotationDictionary[interactable.itemType];

                // Select the appropriate rotation based on the isOn state
                Vector3 rotationValue = interactable.isOn ? rotationSettings.onRotation : rotationSettings.offRotation;

                // Apply the rotation
                interactable.transform.Rotate(rotationValue);```
#

I thought the dictionary was the problem because it has .add

spring creek
cosmic rain
faint nimbus
#

got confused

spring creek
#

It's just essentially a list (not quite) of key value pairs

faint nimbus
#

a bit confused with terms, but i think I get it now UnityChanOkay like .add is to put things inside dictionaries but doesnt really do math commands

#

like add to bookmarks

faint nimbus
#

also, when i do this interactable.isOn = !interactable.isOn; here on

            {
                interactable.onInteract.Invoke();
                Debug.Log("Toggled");
                ///interactable.isOn = !interactable.isOn;
                // Get the rotation settings based on item type
                (Vector3 onRotation, Vector3 offRotation) rotationSettings = rotationDictionary[interactable.itemType];

                // Select the appropriate rotation based on the isOn state
                Vector3 rotationValue = interactable.isOn ? rotationSettings.onRotation : rotationSettings.offRotation;

                // Apply the rotation
                interactable.transform.Rotate(rotationValue);
            }
        }```
it is ok and works fine, but i need to make it so it doesnt flip first without the toggle commands if it is always on so there wont be bugs, like set the xyz to the assigned dictionary and not flip it over and over, but not sure what is causing the adding or flipping over and over, but i have a feeling it is ``interactable.transform.Rotate(rotationValue);`` since it is ".Rotate" and not something like setxyz, i do not know what the function is
worn stirrup
#

Do RigidBodies have a calculatable velocity when the object is being animated?

#

Or would I have to manually calculate per frame if I wanted a velocity to persist when object's being animated too e.e

tall salmon
#

does someone know why my gameobject doesnt move?
this is the code

#

i tried to also move it with the input system and actions but i cant manage to make it work

hexed pecan
spring creek
tall salmon
#

just changed it and it doesnt work still

fervent furnace
#

code beginner problem
also dont use getXXdown and up in fixed update

spring creek
hexed pecan
#

Floats and Vector2s are value types so you need to keep updating them, since you are working with copies. The line in Start will not magically make movement always use those valus

fervent furnace
#

or any function that not running at the rate as update()

tall salmon
spring creek
spring creek
#

FixedUpdate runs at the physics cadence

#

It may happen less than the frame rate

#

Meaning it misses the input entirely

tall salmon
#

so i should change it to Update?

spring creek
#

Yes

#

Always for input

tall salmon
#

alright

spring creek
#

You can get away with it for multiframe input, but not single

tall salmon
#

ill try rn and tell you how it goes

#

i did it but it still doesnt work

frosty widget
spring creek
#

Like I said, just yield return null

frosty widget
#

oh ok

spring creek
#

You are allocating a new WaitForSecons each loop otherwise

#

But other than that, yeah that's what I meant

tall salmon
hexed pecan
# tall salmon

Better update velocity after updating input, not before

#

Otherwise you are working with last frame's input basically

tall salmon
#

but even if i getkeydown it still doesnt do it

hexed pecan
#

Hmm also dont think you should use deltatime here

tall salmon
tall salmon
fervent furnace
#

a frame delay between each input
btw velocity is m/s if you multiply it with s then it becomes m which is displacement

tall salmon
#

it works now

#

i just need to mess a bit with how it works because it glides

#

since i havent made up a good way to make horizontal and vertical = 0 (i think)

orchid abyss
hexed pecan
tall salmon
hexed pecan
#

GetKeyDown is true for 1 frame only. So that else is true for all other frames

#

GetAxis/GetAxis exists too btw

#

Using Vertical and Horizontal axis is pretty common

tall salmon
#

yeah my friend is using those but i want to start as basic as possible

tall salmon
#

so how should i fix it?

#

im thinking of making another variant that is getKeyUp ?

hexed pecan
#

I mean, GetAxis would be simpler

#

Or you can add even more if statements yes

tall salmon
#

i dont know what GetAxis is

#

i´ve heard about it but i dont know how it works

hexed pecan
#

(GetAxisRaw if you dont want input smoothing)