#💻┃code-beginner

1 messages · Page 618 of 1

naive pawn
rich adder
#

new (-1, 1)

naive pawn
rocky canyon
#

not sure if its what ur after.. but u can expand a sprite sheet and select just the sprites u need /want animated from it (Ctrl + Click) and drag into the scene.. (no need to drag the entire sprite-sheet) unless u need the entire sprite sheet

boreal umbra
#

Thanks

rocky canyon
#

took me a minute to realize that myself..

polar acorn
naive pawn
#

well, depends on the context

#

Vector2 delta = new(-1, 1); works just fine

rocky canyon
#

oh neat..

plush kernel
#

I am trying to make a 3D Breakout/Arkanoid game for a uni project right. The one thing I cant do is the ball movement making it bounce around the playarea using Rigidbodies. Internet is no help at all and I'm about to give up and fail this can someone help

naive pawn
#

that's not much info to go off of

#

can you describe the issue in more detail

plush kernel
#

But this is for a 3d version of breakout

plush kernel
#

this is my current code for the ball it starts to work then pushes itself to the left side and stays there pushing against it

using UnityEngine;

public class Ball : MonoBehaviour
{
    Rigidbody Rigidbody;



    void Start()
    {
        Rigidbody = GetComponent<Rigidbody>();
        Rigidbody.maxAngularVelocity = 1000;
        StartCoroutine(ChangeRotation());
    }

    private IEnumerator ChangeRotation()
    {
        while (true)
        {
            Rigidbody.AddTorque(new Vector3(10 * UnityEngine.Random.Range(0, 1f), UnityEngine.Random.Range(0, 1f), UnityEngine.Random.Range(0, 1f)), ForceMode.Impulse);
            yield return new WaitForSeconds(1);
        }

    }

    void Update()
    {


    }

}
polar acorn
#

When it collides with a wall, reflect its velocity

rocky canyon
#

u could even add a bit of randomness then..

#

the torque feels unecessary.. but then again.. im not a pong expert

polar acorn
#

It'd make the ball change its heading every second

eternal needle
polar acorn
#

which I suppose is a way to do a twist on Breakout

polar acorn
rocky canyon
#

who wants predictable patterns in video games anywa

#

lol 😄

eternal needle
safe root
#

!code

eternal falconBOT
naive pawn
#

frame-based issues would arise if frames take more than a second

fleet venture
#

How do i run unity unit tests from the command line?

#

they are editor tests

eternal needle
fleet venture
#

idk what other tests there are but

#

these are editor

#

idk if thats the reason dotnet test doenst work?

safe root
#

So I'm not if there's a better way to do this (Probably is but I'm having problems with anyways). So I am trying to put a collision on this enemy when it dashes but when it does. The collision is compressed and smaller then what it should be and I ain't sure why.

(This has both code I'm using for it.)
https://scriptbin.xyz/ujejezicec.cpp

Use Scriptbin to share your code with others quickly and easily.

naive pawn
rocky canyon
safe root
naive pawn
naive pawn
safe root
tight jungle
#
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float speed;
    private float startPosX;
    private Rigidbody rb;

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            if (touch.phase == TouchPhase.Began)
            {
                startPosX = touch.position.x;
            }
            else if (touch.phase == TouchPhase.Moved)
            {
                float movePosX = touch.position.x;
                float direction = (movePosX - startPosX) / 5;

                rb.linearVelocity = new Vector3(direction * speed, rb.linearVelocity.y, rb.linearVelocity.z);

                startPosX = movePosX;
            }
        }
    }
}

I am trying to make some basic movement on the x-axis for mobile, this so far works great but the movement is really choppy and i don't know how to fix it.

safe root
#

To what?

safe root
rocky canyon
#

also. not sure of ur setup..
but u need to keep graphics seperate from the root object and its logic..

#

esp when dealing with colliders and physics and stuff (want to keep them as close to 1:1:1 as possible)

safe root
rotund bolt
#

question: I have code that manipulates the position of my player in unity using the line transform.position += moveDir * moveSpeed * Time.deltaTime;

when that line references transform.position I am assuming its directly referencing the "Transform" tab/class on the left side of the picture that holds the x,y,z position of my character.

my question is how does transform.position reference those values? when it says transform, it doesn't seem to be referencing an object of the transform class, which is strange cus usually the notation is Object.aVariableOfThisObject. On top of that, I see a public position variable in the Transform class with some get and set code that I don't really understand, but either way, how does the line of code transform.position even reference position if the transform. part isn't even and object? what is lowercase transform even referencing?

polar acorn
#

transform is a variable of type Transform

rotund bolt
#

sorry im a beginner here, are objects named with camelCase

#

im stupid, i thought they were named with PascalCase when created

polar acorn
#

Variables would start with a lower case letter. Classes start with a capital

slender nymph
#

in typical c# standards, public properties should be PascalCase, however unity decided they would rather use camelCase for that. types should always be PascalCase

rotund bolt
#

how does the Player class access this transform object if its not instantiated in the Player class? Where's it coming from? when I look at the definition, it says its coming from the Component class, but how is Player related to Component, i don't see any inheritance there

polar acorn
#

MonoBehaviour is a Component

#

and Player is a MonoBehaviour

rotund bolt
#

oh my god

#

its all coming together

slender nymph
#

UnityEngine.Object > Component > Behaviour > MonoBehaviour

rotund bolt
#

heroes, all of you

fleet venture
#

im trying to follow this guide to get my unity tests working with github actions but im doing something wrong and i dont know what

naive pawn
dusky pike
#

Does anyone know how í could make a particle System work in an UI Canvas ("Screen Space Overlay").

I have these zones and want them to glow... also an "ember" like effect from the sides...

rich ice
#

you'd probably just render them on a different camera and then put the render texture into the canvas. i dont think you can make particle systems work directly on a canvas

dusky pike
rich ice
#

make a new camera. make sure its only rendering the PS's layer. make a new render texture. put the render texture onto the cameras output. put the render texture into a raw image on the canvas

rocky canyon
#

could just make it an image and animte it

#

if u dont u'll probably need to do extra camera work render/texture.. or use a screen-space shader

#

Render/erFeature if URP

dusky pike
rocky canyon
#

slap a particle system in front of the camera and fine-tune it til it works

dusky pike
rich ice
#

ParticleSystem

rocky canyon
dusky pike
#

ah, thanks

rocky canyon
#

this is cool 🙂

#

from what i remember i think ShaderGraph works in all pipelines now.. id need to confirm that

#

nope.. nvm says it can but its limited when used in the regular built-in renderer

fleet venture
#

i dont get what path/to/your/project is supposed to be

rotund bolt
#

everytime i clicked "attach to Unity" in Visual Studio, this pops up in unity and i just click "cancel" each time and it lets me keep using unity and run my code. can i just click "enable debugging for all projects" so this doesnt pop up anymore or would that be bad some how?

slender nymph
fleet venture
#

i thoguht cuz its a unity thing

slender nymph
rotund bolt
unique spear
#

So i can't figure out why is item in my game going to coords 0 0 0 and not to the point where i would like it to be, also it doesn't follow the players movement only the rotation
here's the code:
item.transform.SetParent(centre.transform, false);
item.transform.localScale = new Vector3(7f, 7f, 7f);
heldItem = item;
Debug.Log("item picked up!");
.
i also tried to add this in update but it also doesn't work:
heldItem.transform.position = centre.transform.position;
Debug.Log("pos updated");
.
pls help 🙏

#

could it that the item has no rigidbody?

slender nymph
# rotund bolt for some reason sometimes simply saving my code with CTRL+S doesnt implement the...

i mean yes, it is different than saving because it does more than just save the code, it attaches the debugger to debug play mode. but if you find that simply saving the code and tabbing into unity is not causing it to compile changes then make sure you didn't do something silly like disable the auto refresh for assets, or that some asset (like a Hot Reload asset) isn't fucking with compilation

polar acorn
polar acorn
unique spear
#

its under a player, gimmie a sec

#

the knight is a player

#

centrum is centre

acoustic belfry
#

whats the most simplier and efficient way to display sound?

polar acorn
acoustic belfry
#

like, an easy way to make an object emit a sound

slender nymph
acoustic belfry
slender nymph
#

use an audiosource

unique spear
acoustic belfry
slender nymph
#

next time you should google it, because that would surely be the first result

polar acorn
unique spear
polar acorn
# unique spear

Which object is the first transform? Which one is the second?

unique spear
#

1st is centre 2nd is the sword

polar acorn
#

So, from the looks of it, the sword is at the position of centre

#

there's some rounding errors because of the scale, but that object is at its parent's position

unique spear
#

ok

polar acorn
#

If that's at world 0,0,0, then so is centrum and you'll need to find out why that is there

acoustic belfry
#

ok, how i can make that my enemies (in my 2d game) get pushed to the other side of the damage? like a proyectile or a meele

unique spear
#

i found the problem, it got repositioned after scaling the sword. again thanku very much for help! @polar acorn

regal ridge
#

Hi all, could I ask for help with a problem? I have a Gameobject that I want to prefab. The Gameobject has a script called AbilitySystem which as an array of Abilities . Ability is an abstract class wth concrete subclasses like RangeAttack etc. If I populate the array on my gameobject, make a prefab and then instantiate the prefab the array on the new object is empty. Do I have do serialize something more here? Thank you

slender nymph
regal ridge
#

oh, yes they were scene objects. Will try again with prefabs. Thank you so much for the link and the advice

slender nymph
#

note that the link that was provided would not be useful if you are referencing monobehaviours

rich adder
#

nvm the link lol i misunderstood your q

#

btw might want to check ScriptableObjects though

regal ridge
#

yeah, I will check that option as well. Thanks to both of you

#

short update: Prefabs worked:)

sterile wraith
#

Im doing a car sim and the car needs a mass. Do I have to just select some arbitruary value or is there a way to use a realistic mass for the car

#

so i can take the gameobject itself and maybe utilize density of its volume to find its mass.

rich ice
rich adder
#

when I use wheel collider is not uncommon to use about 3000 to 4000 mass on main rigidbody , which makes sense for a vehicle

sterile wraith
sterile wraith
sterile wraith
#

What does it mean transform.transformpoint is affected by scale?

wintry quarry
#

For example

sterile wraith
#

thats kinda strange

#

so, how could i make it so the distance is consistent?

steep rose
sterile wraith
#

at least i dont think

native thorn
wintry quarry
# sterile wraith thats kinda strange

Not strange. Just think about it. Imagine a ruler at 1:1:1 scale. The centimeter mark is exactly 1 centimeter away from the start of the ruler.

Now scale it up to double size. The centimeter mark is now 2 centimeters from the start of the ruler

#

What do you mean by keep it consistent

wintry quarry
native thorn
#

oh 2d lol oops

ripe matrix
#
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class CombatUI : MonoBehaviour
{
    public GameObject enemyUIPrefab; 
    public Camera mainCamera;      
    public Canvas canvas;             

    private Dictionary<GameObject, RectTransform> enemyUIMap = new Dictionary<GameObject, RectTransform>();

    void Update()
    {
        GameObject[] allEnemies = GameObject.FindGameObjectsWithTag("Player");

        foreach (GameObject enemy in allEnemies)
        {
            if (enemy == gameObject) continue;

            if (!enemyUIMap.ContainsKey(enemy))
            {
                GameObject uiElementPrefab = Instantiate(enemyUIPrefab, canvas.transform);

                Debug.Log($"Instantiated UI for {enemy.name}");

                enemyUIMap[enemy] = uiElementPrefab.GetComponent<RectTransform>();
            }

            RectTransform enemyUI = enemyUIMap[enemy]; 
            Vector3 screenPos = mainCamera.WorldToScreenPoint(enemy.transform.position);

            if (screenPos.z > 0)
            {
                enemyUI.gameObject.SetActive(true);
                enemyUI.position = screenPos; 
                Debug.Log("updated ui position");
            }
            else
            {
                enemyUI.gameObject.SetActive(false);
                Debug.Log("UI is hidden");
            }

        }

        List<GameObject> enemiesToRemove = new List<GameObject>();

        foreach (var entry in enemyUIMap)
        {
            if (entry.Key == null)
            {
                enemiesToRemove.Add(entry.Key);
            }
        }

        foreach (GameObject enemy in enemiesToRemove)
        {
            Destroy(enemyUIMap[enemy].gameObject);
            enemyUIMap.Remove(enemy);
        }
    }

}

Above here, i have a script to display a crosshair over other players. However, when the players are too far away, it doesnt work?

wintry quarry
ripe matrix
wintry quarry
ripe matrix
#

ive tried debug.log in the if else statements for toggling the ui but somehow both are being executed?

wintry quarry
#

well presumably there's more than one enemy

ripe matrix
#

yes

polar acorn
wintry quarry
#

Also maybe you have more than one copy of this script as well

#

So you should log more infomration

#

such as:

  • which enemy
  • which object this script is on
ripe matrix
ripe matrix
#

the rect transform of the crosshair also seems to be right

#

it is enabled as well

#

it just doesn't show when the other player is too far. However, if they move closer, it appears again

wintry quarry
#

and have you tried setting the z of the returned vector to 0?

#

WorldToScreenPoint uses the distance from the camera as the z coord it returns

#

it most likely doesn't make much sense for setting the UI, and it might be putting it out of the renderer's bounds

vagrant pendant
#

hey friendz, does anyone know of resources of how I'd implement "customer AI" for a coffee shop simulator game?

rich adder
vagrant pendant
#

I figured 🫠

rich adder
#

AI in generally something you do once you have some type of system in place already

vagrant pendant
#

I know it's an extraordinarily vague question but I have 0 idea where I'd begin

rich adder
#

Make the system work first without the concept of AI . Eg do transactions manually via UI buttons and such

wintry quarry
#

e.g.

  1. first they arrive at the store and queue up at the counter
  2. once it's their turn, they randomly pick a set of items to order
  3. They wait for the player to fulfill the order
  4. when the order is fullfilled they pay and leave
#

something like that

#

come up with a system

#

when you have designed a system you can think about implementation

eternal needle
rich adder
#

worked on something like this for a sim, I can share some of the line que stuff if you'd like

vagrant pendant
#

I appreciate all the answers – @rich adder that would be supremely appreciated

rich adder
#

gotcha. one sec I'll pull it up. ofc there are millions of ways to do too

ripe shard
rich adder
#

behaviour trees def overkill

ripe shard
#

why?

#

its not that its a particularly complicated idea

#

or implementation even

sour fulcrum
#

i know it's kinda been mentioned before but also keep in mind that you are asking this to a room of programmers. depending on your game and what it actually needs you could end up needing something that's like 95% less complex than anything someone here is gonna offer (doesn't make those options any less valid ofc)

rich adder
# ripe shard why?

I guess with new behavior tool unity has might be easier to do actually

ripe shard
#

dude, a behaviour tree is like the simplest thing ever, it doesn't have to have a visual editor

rich adder
#

ya for some its just easier to do with an actual UI tool too

sour fulcrum
#

i wouldn't call a behaviour tree "the simplest thing ever" considering the average post made in this channel, no offense to anyone

rare basin
rare basin
#

why are your enemies tagged as Player

#

kinda confusing

sour fulcrum
ripe matrix
vagrant pendant
rich adder
#

so its just a list you can keep track and move the line with the Next on the array.

wanton hearth
#

I am trying to use Vector3.Dot to detect when the hand of this clock hand thingy gets to the 45 degree position. I can do it for the 12/6 oclock positions using transform.up and -transform.up, but having trouble with in between positions. How would you get a 1:30p vector, for example, originating from the center of the clock? (It's a 3D object but just rotating around one axis)

teal viper
hallow rock
#

Hey. Trying to find how to add others to my Unity Project. Can anyone help?

sterile wraith
sterile wraith
# wintry quarry What do you mean by keep it consistent

well, in the suspension im designing, I have the max height for the top of the tire (where the x is). and that is basically the chassis + a little offset. and wherever the car is , I always want that offset to be the same relative to the car. so i thought to do transform.TransformPoint(car.localposition + transform.up * maxWheelHeight) to get that position, but because of scaling it isnt actually where its supposed to be.

lusty flax
#

for some reason, the part of the code with the "roll()" function triggers multiple times after Z is pressed despite the fact that "rolling" is never set back to false (in any part of the code)

{
    if (running)
    {
        if (!rolling && activated)
        {
            rolling = true;

            crank.SetTrigger("Crank");
            roll();
        }
        else
        {
            if (Input.GetKeyUp(KeyCode.Z))
            {
                activated = true;
            }
        }
    }
}```

why is this happening?
slender nymph
#

how have you confirmed any of that

lusty flax
#

the crank thing is an animator so it tries to trigger the animation in quick succession and results in errors

#

however the animation still plays once before the error

#

so that part of the code is triggering multiple times

#

i think

rich adder
#

not even a log to check it prints twice?

slender nymph
#

you very likely have more than one copy of that component in the scene, because if that crank.SetTrigger line is the one throwing the NRE then it cannot possibly be properly setting the trigger

#

so the only explanation is another copy where crank is not assigned

lusty flax
#

yea thanks for some reason there were various copies of that script in elements that were not meant to have them (idk how they got there 🤷‍♂️ i probably hovered over them by accident or smth) and deleting them fixed the issue
thanks 👍

brittle isle
#

Having issues with applying ice physics in my platformer. It's like my player doesn't slide at all even when the function for it is called

slender nymph
#

you're gonna need to provide more information because you can't just drop nearly 1000 lines of no syntax highlighted, barely formatted, code and expect anyone to want to dig through it to figure out what's wrong with it

brittle isle
#

That,s the part that baffles me. In it, I call a ApplyIcePhysics function to when I'm on tilemaps tagged ice on the ground layer. The catch is that maybe my calculations for slowing down and gaining speed on ice are wrong, and so it's like my function doesn't even exist even when the log clearly says it does, feeding me the variables.

sour fulcrum
#

you gotta use a proper pasting site, for starters

brittle isle
#

such as?

#

I'm at a loss for my ice physics...

sour fulcrum
#

!code

eternal falconBOT
brittle isle
#

thanks!

#

Here is the code for my player. I wonder if my other methods are part of the issue

obtuse ether
#

trying to make an ammo UI thing

#

so i just made an image w 10 bullets in a row

#

and dragged it into an image so i could use fill to make the bullets in the line slowly dissapear

#

but its only showing one bullet

#

and its showing each bullet like this

#

i think i accidentally found out how ppl make animations in unity 2d 💀

#

but yeah how would i make it just show the whole imagae

slender nymph
#
  1. this is a code channel
  2. if you want it to act as one sprite, then do not set the sprite mode for the texture asset to Mulitple
obtuse ether
#

which channel would i put it in normally lol

slender nymph
heavy knoll
swift elbow
heavy knoll
swift elbow
#

there is a built in splines package, if you arent already aware

heavy knoll
#

also is that package already in my project by default or do I need to search it in the package manager and install it?

swift elbow
#

well, you can do anything from scratch as long as youre capable enough

#

you dont NEED this package

#

but it'll be a lot easier if you do use it

heavy knoll
#

ok, yea im still learning lol, not too expenienced yet, but I'd like to try and learn how to do it myself if i can since it'll prob be more useful in the long run

#

are there any hard limitations to doing large scale procedurally generated splines on my own?

#

just kinda stuck a bit on which way I should go about doing certain things, cause I dont wanna get stuck behind limitations which would have to make me redo the whole system.

swift elbow
# heavy knoll are there any hard limitations to doing large scale procedurally generated splin...

when messing around with the built in splines package myself, i notice that it becomes increasingly more resource heavy the more complex a spline is. im not sure if this is something that you can overcome by implementing your own custom system, but it's definitely something to be wary of, at the very least. this is not to mention the complexity of the math that goes into making splines in the first place

swift elbow
heavy knoll
swift elbow
heavy knoll
#

main thing I'm struggling with in code rn is that whenever I try and think of something I wanna put in and cant figure out how to do it on my own, i try and lookup a solution and once I find it I feel like there was zero chance I was gonna be able to know how to do that without looking it up

heavy knoll
#

u have any pointers for good spline resources?

swift elbow
swift elbow
#
  • Freya is a unity dev too
heavy knoll
heavy knoll
pure drift
swift elbow
#

use a foreach loop

pure drift
#

would i use something like this: foreach(hit in _hits)

#

i changed it to _for more clairty for me

swift elbow
pure drift
obtuse ether
#

using this code to make the bullet UI show how many bullets are left in the gun

#

but for some reason i keep getting 0

#

i even checked the values of current and max ammo and got the right numberrs

#

so why is dividing the two making 0

swift elbow
obtuse ether
tawny grove
#

is the best way to get the length between two positions just a^2 + b^2 = c^2

frosty hound
#

There is a Vector3.Distance function you can use

bright gulch
#

i often want to clone my projects, is there a good way to do this?=

frosty hound
#

If you're using version control, which you should, you can just re-clone the repo to a new folder.

#

Otherwise, if you aren't, just copying the entire project folder. 🤷‍♂️

bright gulch
#

i always copy the folder, and then... there is always script problems

#

its like the old scene and scripts are still in the memory

rocky canyon
bright gulch
#

oh

#

that is better i think

rocky canyon
#

then i'll go into project settings/preferences and rename it there too to finalize it

bright gulch
#

then u have to reinstall all the imports

#

ah

rocky canyon
#

delete the old .sln files n whatnot and let the IDE make a new one w/the new project name

rocky canyon
bright gulch
#

.sln file, what does that do?=

rocky canyon
#

if they're regular assets u already have in ur project folder it should be fine..
sometimes i gotta redo a TMPro font or something but thats ez

bright gulch
#

oh okay

rocky canyon
bright gulch
#

okay

#

great, so this might be my problem now

#

where can i find that file

rocky canyon
bright gulch
#

oh

rocky canyon
#

when u re-open a script from the new project you'll get a new one generated w/ the new name

#

if u don't is fine too.. you'll just end up with (2) of em

#

i think u can do it w/ that button as well ^

rocky canyon
rocky canyon
bright gulch
#

is it hard to att the project to a git-hub repo?

#

in fusion 360 u middle click and then it focuses around that point, what is the same command here in unity

bright zodiac
#

Tuple/valueTuple vs KVP are fortunately not the same or even on par

KVP doesnt implement IComparable and IStructuralEquatable. for element wise comparison both tuple and valuetupple surely have more advantages.

Also in terms of hashcode uniqueness tupples are more superior

#

(hmmm.. why i keep replying old messages here?)

sour fulcrum
#

though they did say basically and similar

bright zodiac
#

fair 👍

verbal cedar
#

I used a guide to make this kick hammer recently, also anyone know a good app/program or content creator that has guides on coding C# in unity? (for complete beginners) I want to get better.

eternal falconBOT
#

:teacher: Unity Learn ↗

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

naive pawn
#

or, checkpins

eternal needle
proper yacht
#

Why Jumping not working? I wanna set jump action within inspector

    [SerializeField] private string jumpButton = "<Keyboard>/space";

    private InputSystem_Actions _inputSystem;
    private InputAction Jump;

    void Start()
    {
        _inputSystem = new InputSystem_Actions();
        ChangeBindingButton(jumpButton, "Jump");
    }

    void ChangeBindingButton(string newButton, string actionToFind)
    {
        Jump = _inputSystem.FindAction(actionToFind);
        Jump.AddBinding(newButton);
        Jump.Enable();
    }
naive pawn
#

as in, you can't change the binding? or you aren't jumping?

mortal ginkgo
#

i didn't know where to put this
WHY DO MY PROJECTS START WITH ALL THIS STUFF???

naive pawn
#

that's normal

mortal ginkgo
#

WHY

naive pawn
#

it's the stuff unity comes with

#

clam tf down

mortal ginkgo
#

clam

#

ok clam made me calm down

verbal dome
#

clam down crabs

mortal ginkgo
#

but it doesn't help me learn when there's so much stuff unexplained

verbal dome
#

All (most) of it is documented online if you search

mortal ginkgo
#

i came here from godot when i learned that the college courses i'm going for are in unity

verbal dome
#

You can check out !learn to get a headstart

eternal falconBOT
#

:teacher: Unity Learn ↗

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

mortal ginkgo
#

shut up unity dyno bot

#

is unity learn the best place to start learning?

naive pawn
#

yes

#

and the bot is actively responding to the command osmal used

#

osmal triggered the bot to link you to unity learn

west radish
astral falcon
# mortal ginkgo but it doesn't help me learn when there's so much stuff unexplained

Keep digging, thats whats learning about. Not learn to repeat what you get told in the first place. You dont understand a word of something explained? Google it, learn how to use the docs. It all is a bigger picture of your learning curve resulting in the tools you need to solve problems instead of always looking for a premade solution. 🙂

last owl
#

I have a simple script that spawns enemies at a number of locations randomly which is done by having an array of empty game objects and choosing a random number from 0 - array.length then selecting the specific empty game object and getting its transform.position then spawning the enemy there. The script seems to work and spawns the enemies but for some reason I get a "IndexOutOfRangeException" everytime a spawn happens even though it works fine. I can't seem to work out what's wrong?

[SerializeField] private GameObject enemy;
[SerializeField] private GameObject[] spawnPositions;
private bool startSpawn = false;

// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
    startSpawn = true;
}

// Update is called once per frame
void Update()
{
    if (startSpawn == true)
    {
        InvokeRepeating("SpawnEnemy", 1, 3);
        startSpawn = false;
    }
    
}

private void SpawnEnemy()
{
    int randomSpawnPos = Random.Range(0, spawnPositions.Length);
    Instantiate(enemy, spawnPositions[randomSpawnPos].transform.position, enemy.transform.rotation);
}
burnt vapor
#

Since arrays are zero indexed, the length must decrement by 1 to avoid overflowing the last index

#

For example, assuming your array has one entry, you effectively try to get entry index 0 or 1, meaning 1 overflows.

last owl
#

Its still giving me the error and now it doesnt spawn at the last location in the array

sour fulcrum
burnt vapor
eternal falconBOT
burnt vapor
sour fulcrum
#

float is inclusive max is exclusive, check that link

burnt vapor
#

Lol Unity

#

They never learned the word consistency

sour fulcrum
#

i assume its differently specifically for this kind of usecase where your using a collection index

keen dew
burnt vapor
#

@last owl nevermind the previous point, decrementing does not solve your issue

wild island
#

is disabling the collider of a certain object before doing a raycast and then enabling it again going to work reliably? Does it have performance impact?
I can't use layers here

astral falcon
#

Woops, wrong mentioning 😄

last owl
#

Its weird because it works but gives me the error every time

keen dew
#

To be fair the standard C# Random.Range is also max exclusive

#

Random.Next I mean

sour fulcrum
#

its inconsistent but makes sense i guess

astral falcon
sour fulcrum
#

i wonder how many games have slightly/not slightly off random rolls because people don't know it's exclusive and are accidently excluding their last entry

last owl
#

IndexOutOfRangeException: Index was outside the bounds of the array.
Game_Manager.SpawnEnemy () (at Assets/Scripts/Game_Manager.cs:29)

#

It just prints that every spawn

astral falcon
burnt vapor
#

And index 0 will not exist

last owl
#

Sorry im a beginner you're gonna have to explain what you mean by "logging it"

astral falcon
burnt vapor
#

Try changing your code to this @last owl

private void SpawnEnemy()
{
    Debug.Log($"Length: {spawnPositions.Length}");
    int randomSpawnPos = Random.Range(0, spawnPositions.Length);
    Instantiate(enemy, spawnPositions[randomSpawnPos].transform.position, enemy.transform.rotation);
}
keen dew
hot harbor
#

My bad, I think I'm not quite understanding everything that's going on here, what is it exactly that this is trying to do?

burnt vapor
#

My guess is it either logs twice, or once and length is 0

last owl
#

yep it logs twice

astral falcon
#

well

last owl
#

first one is the correct one second is just 0 for some reason

#

Why is that happening?

burnt vapor
#

You have the script on two components

#

Change the code to this:

private void SpawnEnemy()
{
    Debug.Log($"Length: {spawnPositions.Length}", this);
    int randomSpawnPos = Random.Range(0, spawnPositions.Length);
    Instantiate(enemy, spawnPositions[randomSpawnPos].transform.position, enemy.transform.rotation);
}
#

Then you can click the log message and find where it is defined

#

Then just remove the invalid one

last owl
#

They both lead to the same object

burnt vapor
#

Then you have it defined twice

#

Scroll on the component and it's there twice

#

Alternatively you somehow manage to empty the array and then the code calls it a second time

last owl
#

Oh my god I have no idea how that happened but the script was on there twice LOL

burnt vapor
#

Good job team

last owl
#

Thanks

burnt vapor
#

Now you know how to easily find stray components

last owl
#

I have learnt something new today

fleet venture
#

I want to run a method an x amount of seconds after i trigger it, how do i do that? i can only find stuff for repeating and i only want it to happen once after a trigger and then not untill its triggered again

fleet venture
#

let me see

#

oh ye

#

that looks good

final kestrel
#

!code

eternal falconBOT
final kestrel
#

I have this script that is responsible for loading my Loading_Scene first then inside starts loading the scene I pass in. When I start my game. It succesfully loads the First scene with loading screen scene. But through my game when I want to load another scene using Loader class. It gets inside the OnLoaderCallback but never starts the coroutine. So basically I cannot use the Loader.LoadScene twice through my game. It only works once.

astral falcon
final kestrel
#

No not at all

#

I thought maybe I was giving the string wrong but It is the same as my scene

astral falcon
#

Does your log get fired in the coroutine?

final kestrel
#

Yes if it succesfully fires the coroutine I see the message. But when I try using the loader class again no. Doesnt call the coroutine

astral falcon
#

Did you check your gameobject, if its created?

final kestrel
#

Yes I did. Its there

astral falcon
#

And it never gets destroyed I guess?

final kestrel
#

I already have it on my Loading Screen scene. Before creating it in the code too

#

I thought it could be related with how I flag the booleans but I cant wrap my head around

#

Because it wouldnt get inside the OnLoaderCallback at all if that were the case

astral falcon
#

So the onloadercallback, that you assign a method to, is called?

final kestrel
#

Yes it logs the first message

#

saying it works I mean

astral falcon
#

When does that log happen. On the first load, right?

final kestrel
#

Second too

astral falcon
#

So first is not loaded default scene and second call is the loaded scene?

final kestrel
#

So my first scene is my menu scene. When I press play I call Loader.LoadScene. It works as its expected to. Then I play my game and have to use the Loader again to load another scene.

#

Then it does get inside OnLoaderCallback but never unloads the other scenes or loads the next scene. I'm still on the Loading_Screen scene.

#

When I dont start from my Menu scene and not load. Starting straight from my playable scene. Loader class works cause im using it for the first time.

native widget
#

I have colliders on the island "floor". Is it possible to do something like a ReverseRaycast that will get the position where there is no more land?

#

rather than making an ocean collider

astral falcon
final kestrel
#

Inside the LoadSceneAsync method. At the bottom. I'm calling Unload scene. Which checks current scene and some other scene that is not present anymore. And unloads the rest

astral falcon
#

That naming is misleading 😄 But okay, found it

final kestrel
#

Yeah sorry about that.

astral falcon
#

So your code created prefab, is not created after your first scene was loaded correctly?

hexed terrace
final kestrel
#

I already have a game object with the loader call back script attached to it in my Loading screen scene.

#

Its not a prefab

astral falcon
#

yeh, not prefab. GameObject, my bad. But you create it everytime you enter a new scene and your update is called first. And then you try to destroy it right after if its loaded (which it should I assume, as the scene got entered?)

native widget
astral falcon
#

Why not use another layered collider to check against?

#

Water != land

hexed terrace
final kestrel
#

I dont see it get destroyed

hexed terrace
#

you destroy it in code

final kestrel
#

Yes I do I was checking if it got destroyed in the hierarchy

hexed terrace
#

I dont get why you'd create and destroy this every load

final kestrel
#

Well to be fair. I followed a video for this from Code monkey.

#

This is what he does I mean

hexed terrace
#

I understand

astral falcon
#

Tbh it is kinda hard to read the code. Not to udnerstand, what its doing but just to follow. Like having your callback setting a loading state to false is wrong, as the callback should never dictate the actual state its waiting for for example. You should really, after understanding the code, clean it up a bit. As Carwash said, no need, to have one MB and GO created all the time, just make it a DDOL and listen for scene changes for example.

final kestrel
#

I see. Well I do not get why I keep creating and destroying a game object that already exists in the scene either. Also yeah I need to be specific with the names and such sorry. I thought it may be because it destroys the object without even starting the coroutine but yeah. Thanks for the help!

astral falcon
#

You also seem to be destroying your loading scene with your SceneManager loop, could that also be the case?

#

ah no, thats happening after the load. phew, yeh, its kinda ping pong in the code going on 😄

final kestrel
#

Yeah I'm also having hard time navigating. I'm really sorry about that 🙂

#

What is weird is that why does it work the first time.

astral falcon
#

Nah, its fine. Its all part of the learning curve 🙂

#

I guess, your assumption about some boolean or whatever not being correctly reset or soemthing might be the issue. But I 100% bet, rewriting to your own needs and with your own understandable structure and naming is less time consuming then trying to understand the structure the tutorial provided 😄

final kestrel
#

Yeah that I agree. I could just load my loading screen scene then load the next scene non additively but I just wanted to make this work cos I had a Init scene previously I wanted to keep.

astral falcon
#

You can of course take parts out of it. But as you said, you know, what you actually need.

final kestrel
#

I simply refused to accept the defeat but yeah. Thanks for your time I'll find a workaround!

astral falcon
#

haha, yeh I know that feeling. But you yourself already found out, that the code was not optimal, so you are able to write a better one 🙂

final kestrel
#

Well I hope so. Haha we'll see!

terse niche
#

I was trying to add an AimCamera, turn out I can't move my camera anymore (the aim zoom style running but I can't move anymore)

grand snow
terse niche
#

I have to restart everything ?

bitter apex
#

What is a good way to truncate positions of a vector? Math.Truncate() seems to be doing funky things for me, with the top value being the Math.Truncate()'d version and the bottom being the world position of the vector

#

I guess I could also cast it to an integer and then back to a float..?

timber tide
#

There's Vector3Int if you want to just use ints

wintry quarry
#

Just for logging or display? Or what?

#

Also showing the actual code you did would help us explain why you're seeing weirdness

cosmic dagger
#

Use Vector3Int instead. If you cast to an int, the values under 0 will be 0 . . .

little seal
#
    Vector3 GetClickedPos(out RaycastHit hit)
    {
        Vector3 target = Vector3.zero;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
        {
            if (!IsPointerOverUIObject()) target = hit.point;
        }
        return target;
    }

why does this return a height of 0? shouldnt it be .5 the object im hitting has a transform at 0 and the box collider and scale is 1 thick
it does return the right x and z

bitter apex
#

i need to round to the nearest integer to 0, so like 21.65 to 21. -17.93 to -17. my actual vector can't be an integer though as I'm adding 0.5 to each component of the vector

bitter apex
#

i need negative values too

wintry quarry
#

What are you doing with them

bitter apex
#

I'm just trying to get a vector, that's literally all I'm doing

wintry quarry
#

To do what with

#

Sounds so far like you could be using Vector3Int

#

But truncate would work if used correctly

#

Or Round

#

Or Ceil

#

Or Floor

#

Depending on the requirements

cosmic dagger
#

Use Mathf.Floor then . . .

#

Or FloorToInt if you want the result to be an int . . .

polar acorn
#

Cast it to Vector3Int when you need the ints, but keep it as a float for your computational purposes

bitter apex
#

Okay, thank you.

bitter apex
polar acorn
little seal
polar acorn
#

Did you log that inside or outside of the IsPointerOverUIObject check? If that's true, it won't change target from its default value of 0

cosmic dagger
#

But as Praetor suggested, telling us why you need to do this can help you find the appropriate solution . . .

polar acorn
little seal
polar acorn
little seal
#

alr thanks ig

#

not sure what changed but if it works it works :)

scarlet skiff
#

why wont stick follow the player when moving despite it being a child of playerCapsule? like, what do i need to check?

timber tide
#

more information

scarlet grove
#

hi was wondering if anyone can help me here please understand why unity is saying that this private void isnt correct i am doing unitys rollaball course

timber tide
#

You're nesting methods which you probably don't want to be doing here

scarlet grove
timber tide
#

It means don't create methods/functions inside of other methods

scarlet grove
scarlet skiff
# timber tide more information

playerCapsule has a rb
so does the stick.
nothing changes the position of the stick in the code except for this upon collision:
itemComponent.transform.localPosition = Vector2.zero;

when on ground its gravity is 1, upon collision it gets set to 0.

and this is the method that moves the player:

void  OnMove(InputValue value) 
{
    Vector2 input = value.Get<Vector2>();
    // If any horizontal key is pressed, use its sign (1 or -1), otherwise 0.
    float horizontalInput = input.x != 0 ? Mathf.Sign(input.x) : 0;
    moveInput = new Vector2(horizontalInput, 0f);
}
timber tide
# scarlet grove how would i go about fixing that ?

You should find yourself some tutorials to follow. Sorry, I'm not that great at throwing resources at this stuff, but you're obviously somewhat new at c# and you're just going to run into more issues until you learn it properly, and jumping right into Unity without knowing what's wrong here just going to make your life even more difficult on your path on learning.

scarlet skiff
eternal falconBOT
timber tide
scarlet skiff
timber tide
#

Disabling is fine, yes. If say you wanted to use the stick as a weapon with physics and a child to the player -> requires some custom logic

scarlet skiff
#

oh wait u cant enable and disable rbs

#

i guess kinematic it is then?

timber tide
#

Yeah, if it's like an inventory thing where you're storing these objects you can probably just switch kinematic on and off

scarlet skiff
timber tide
#

If you wanted to use the stick as a weapon, stick to kinematic

#

but if you were to drop it on the floor and want that physics, then you can toggle it like that

scarlet skiff
timber tide
#

Usually you use the animator too when it comes to weapon attacks anyway, but I guess you probably manage something through code

#

there's actually some benefit of using kinematic vs just animation, but that's a pain to really do

rotund bolt
#

wokeup to see my whole project is kinda gone(?) despite it working fine last night and I saved it too when i exited. anyone had this? it asked me to enter safe mode when i opened it btw so i did, but then i closed it and reopened it and clicked ignore the second time

timber tide
#

but remember that collision isn't handled when it's kinematic, but you will still get callbacks from the OnTrigger methods

grand snow
scarlet skiff
timber tide
#

Kinematic doesn't handle any sort of collision. If you added velocity like gravity to it, it'll clip through the ground unless you tell it not to

#

It will however notify you that "hey, I touched ground just so you know"

rotund bolt
scarlet skiff
grand snow
timber tide
scarlet skiff
#

or so i think, its my first inventory that i make

polar acorn
grand snow
#

i think they got it now

rotund bolt
timber tide
# scarlet skiff or so i think, its my first inventory that i make

another idea too is just destroy the actual item when you pick it up and store it as data if we're talking about a UI representing the items. And, when you drag the UI element out of the inventory to drop it you would instantiate this rigidbody scene element again. But, if you're not making an infinite inventory, it's fine to just stash the monobehaviours

grand snow
rotund bolt
#

most definitely

scarlet skiff
# timber tide another idea too is just destroy the actual item when you pick it up and store i...

yes but there is also the pickedup state is a li lcomplex because i want the itemto be usable as well, that u can see the player holding it etc, so what i did is that once picked up, i disabled all its hitboxes, and as u now know change rb to kinematic, and parented it to the player, i do that will all items, just that the only visible one is the selected item. i assume there are more effecient ways but oh well, i also only have a hotbar in the game no full on inventory, so this works fine i think

slow knot
#

whats a good way to make a first person camera script, i made one using lockcursor but it is very choppy and im wondering what the alternatives are

queen adder
#

What's should i use to prevents the Chain(-Joints) from breaking, when moving with the Player (The Ball) with WASD. i tried rb.velocity and rb.AddForce. Both break the chain. (More Details in #⚛️┃physics )

slow knot
#

im just gonna uh, steal danis first player camera script...

burnt vapor
#

These questions are so easily solved if you take a few minutes to fix your editor, and it also saves us time

scarlet grove
#

its all sorted now

burnt vapor
#

I really doubt it

scarlet grove
#

well its now working better than it was

rotund bolt
#

i notice when i manipulate objects in unity "scene" section while my game is running that the chnages dont save when i stop the game from running. is there a way to make it save like that or should i avoid that for some reason

burnt vapor
wintry quarry
#

you could make a way to do it for some specific use case

#

one cheeky way also is to copy the object or component values at runtime

#

and paste in edit mode

#

there may also be plugins for this

scarlet grove
#

if you would like to help me get it all set up properly i would really appriciate that

burnt vapor
#

Well the bot message explains it really well. You'd know it works because the code now properly highlights faulthy areas

scarlet grove
#

any recomendations to learn it

slow knot
#

i mean hes gotta start somewhere, maybe he just wants to make games

eternal needle
scarlet grove
#

thank you and going by unitys website i am doing it in order by doing rollaball first then programming

eternal needle
#

i do recommend learning some c# outside of unity first, so you aren't trying to learn 2 things at once. the microsoft learn site is also pinned (intro to c#)

scarlet grove
#

i will take a look at it i take it thats more bases on just programming and syntex rather than doing it in unity and trying to learn adn make something do something at the same time

rotund bolt
#

if i delete an object in unity like a cube or something, does it go to a "trash" where i can undelete it? or delete it forever?

polar acorn
#

You could Ctrl+Z it as long as you haven't closed the program

#

Or done enough stuff that it's out of the undo buffer

eternal needle
scarlet grove
rich adder
#

this video isn't enough to help with anything

#

idk ? how about more details on the setup and things like the code.. people shouldnt have to play detective , you should provide everything someone needs to understand the setup

rough lynx
#

It's something they have to account for themselves

rich adder
rough lynx
#

You learn to spot that kind of stuff when the communities you're in are full of people who make low quality monkey games

burnt vapor
#

Did you install the editor through Unity or manually?

slow knot
#

yeah im having issues learning becasue half the words that are and arent syntax that is said on overflow sounds like wizardry, is there any like post somewhere that just explains a lot of coding terms because i cant understand a word of what is said

rich adder
wintry quarry
slow knot
#

the only thing that can really dumb it down enough for me is AI and people dont recommend you to use AI since its really bad

wintry quarry
#

AI can be helpful for understanding terms. As can asking people about those you are confused about

rough lynx
#

Yeah. Really irritating how instead of innovating people just download that loco and plaster their game on the Meta Store. EVERY new game is a Gorilla Tag clone on the Meta Store

rich adder
rough lynx
slow knot
#

its stuff like quaternion, like i have genuinley no idea what quaternion could mean.l it sounds like my phones CPU

#

or slerp

rough lynx
#

Sorry if I'm coming off as harsh you can only see so many of those kinds of games before it drives you up the wall

slow knot
#

damp

rich adder
wintry quarry
slow knot
#

i kinda understand damp but also not in half the scenarios

wintry quarry
#

like how Vector3 can hold a position
Quaternion holds a rotation

#

that's it

polar acorn
wintry quarry
polar acorn
# slow knot damp

"Damping" is a term for just generally "Making something smaller and smaller over time"

wintry quarry
#

it can also be used in the context of smoothing things out

#

like for cinemachine cameras

polar acorn
#

It's not really a programming term, it's just a word

slow knot
wintry quarry
#

We jus shared some examples

slow knot
#

but like damp time, you cant smooth out time?? or can you idk im not the professional here

wintry quarry
#

what do you mean

#

when is anyone saying "damp time"

polar acorn
polar acorn
slow knot
#

You can also adjust the damp time to change how smooth your transition is. This function will also automatically account for player movement mid-lerp.

like this, this comes from a stack overflow post

wintry quarry
#

A specific function?

#

You need to pay attention to the context

#

we have no idea what you're talking about

#

SmoothDamp?

slow knot
#

yeah it was just an example on where i found it and why i brought it up. maybe a bad communication on my part

wintry quarry
slow knot
#

just in general on how in the hell im supposed to know what all of these "random" words are everywhere in stack overflow

wintry quarry
#

what random words

scarlet grove
slow knot
wintry quarry
slow knot
#

thanks ill get back to work now

polar acorn
#

Or just, like, context clues.

#

Like how you'd learn any new words

queen adder
#

Why is my trigger not working? Parent: Rigidbody2D, Collider2D (ex. Rope-Layer, so that it doesn't stick to itself all the time) Child: Colider2D set to Trigger With Script ```cs
public class ropeTrigger : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.layer == 6) {
Debug.Log("Collision mit Rope");
} else {
Debug.Log("Collision");
}

}

}

burnt vapor
#

Check VS is the default Unity editor

#

When neither is the issue, regenerate propject files

wintry quarry
queen adder
slow knot
#

what does Mathf, ref and just in f in variables mean

queen adder
#

thanks hahah

slow knot
#

oh

wintry quarry
#

2f is two as a float

#

Mathf is math for floats

#

ref means to pass the parameter into the function as a reference instead of copying it

polar acorn
polar acorn
surreal minnow
#

I have a ledge grab system and the issue is that I want the character to end up at the end of the climb up animation but I would have to have "Apply root motion" enabled but that would break everything else. Anyone know a solution?

wintry quarry
# slow knot oh

If I do:

void Test() {
  int x = 5;
  Change(x);

  print(x); // this will print 5
}

void Change(int num) {
  num = 10;
}```
it will print 5.
But if you do:
```cs
void Test() {
  int x = 5;
  Change(ref x);

  print(x); // this will print 10
}

void Change(ref int num) {
  num = 10;
}```

It will print 10, because since it's a reference we can change the variable from the caller.
polar acorn
wintry quarry
scarlet grove
naive pawn
#

no

#

we don't do DMs here

surreal minnow
#

Are animation events asynchronous?

polar acorn
eternal falconBOT
wintry quarry
slow knot
wintry quarry
#

so discord can embed

burnt vapor
#

Check the bot command above

slow knot
#

uh, how do i do that im new to obs

#

lemme look

naive pawn
surreal minnow
naive pawn
#

and could you be more specific as to what issue you're having

wintry quarry
#

OBS can convert it

surreal minnow
#

instead of checking it every frame in update()

wintry quarry
#

there's a menu option

naive pawn
#

i think my discord died for a sec there, sorry

scarlet grove
wintry quarry
polar acorn
#

you can look at it when you actually intend to follow it

naive pawn
surreal minnow
surreal minnow
#

Thank you

#

oh nvm not for me lol

#

oh nvm it is thanks xd

slow knot
#

heres the mp4

shut warren
#

Hello, can someone help me with something about camera rotation and change directions? Like, when I rotate my camera, the player direction chage, like if I'm stiff facing noth and walking to the north and I rotate my camera, my player still walking forward (I don't know if it is understanding)

surreal minnow
#

Is there no events for animation ends/stop or do I need to make the logic myself?

shut warren
wintry quarry
#

it's whatever code you're using to rotate your player

#

Also potentially because you haven't enabled interpolation on your player Rigidbody

#

(if you haven't)

#

Oh yeah sorry it's this:

        playerBody.Rotate(Vector3.up * mouseX);```
#

You can't rotate a Rigidbody via the Transform

#

unless you want it to be jitter city

#

instead do:

myRigidbody.rotation *= Quaternion.Euler(0, mouseX, 0);```
slow knot
#

you are a godsend, i hope you win the god damn lottery, thank you 🙏

#

i watched a video about yandere devs code and it said i should not initialize a module more than once if not necessary right? what do i do instead of that

wintry quarry
#

What do we mean by initializing modules in this context?

#

What "module" are you initializing right now and when and where are you doing it?

slow knot
#

i realize now that it probably isnt the issue but just in general, oh yeah its GetComponent<componentname>(); not initialize component

#

too much python in my brain

surreal minnow
#

Can anyone explain what component makes this pill hitbox? I need to disable collision temporarily

rich adder
surreal minnow
#

Is there a property to disable its collisions?

wintry quarry
#

Disable it

#

what do you mean exsactly though

#

like other things colliding with it

#

or it colliding with things when it tries to move?

surreal minnow
#

Yeah when i climb the ledge of a cliff the hitbox is pushing against the terrain

rich adder
#

you can like Nudge it up or down depending where you want it to go

wintry quarry
surreal minnow
#

Yes I will show a video clip one moment

#

Seems to be pushing against the terrain, not sure how else to do this other than to disable collision temporarily

wintry quarry
#

but no the CC will not "push against" terrain really unless it's moving via Move()

surreal minnow
#

Well I tried but it doesn't disable it. I put

GetComponent<CharacterController>().detectCollisions = false;

Inside Start() and the character should fall through the map, no?

rich adder
#

why not just GetComponent<CharacterController>().isEnabled = false

#

https://docs.unity3d.com/6000.0/Documentation/ScriptReference/CharacterController-detectCollisions.html

This method does not affect collisions detected during the character controller's movement but rather decides whether an incoming collider will be blocked by the controller's collider. For example, a box collider in the Scene will block the movement of the controller, but the box may still fall through the controller if detectCollisions is false. This property is useful to disable the character controller temporarily. For example, you might want to mount a character into a car and disable collision detection until it exits the car again.

rich adder
#

im confused why its not working then so Id say just disable it lol

wintry quarry
#

GetComponent<CharacterController>().enabled = false; is how you disable it @surreal minnow

surreal minnow
#

Well the issue with that is:

wintry quarry
#

correct

#

don't call Move on a disabled CC

rich adder
surreal minnow
#

But that would disable air strafing, wouldn't it?

rich adder
#

yea

#

so maybe disabling the entire thing might not be what you want

wintry quarry
#

are you supposed to be able to air strafe while doing the climb animation?

surreal minnow
#

No but Id imagine in the future I would want to be able to move left or right while grabbing the ledge

rich adder
#

you could always use raycasts so when you move left and right you dont phase through walls while collider is disabled

#

like everything in development comes with its own compromises for each solution, either have a solid controller and manually deal with offsetting it.. Or disable it but that causes youto not bump into colliders at all which will make you phase through them unless you use a prevention like stopping movement with ray detection

polar acorn
#

Seems like you might simply not want to use the CharacterController

#

It really is only meant for incredibly simple movement and it sounds like you want something more granular

surreal minnow
#

You are probably right about that^

rich adder
#

CC is still very much easy to use for collision detection and steps / slopes

#

something you'd have to manually code when on ground

#

even RB makes this annoying as hell in comparison

fallen jacinth
#

Hello everyone everytime i install unity it's stuck at this

rich adder
#

also wait a while

fallen jacinth
#

oh

surreal minnow
#

Well I have to switch from it if I am not able to do something as trivial as disabling its collisions

rich adder
surreal minnow
#

But it disables the whole component, not just collisions

#

I guess I can try making the collision box size 0 and see if it works

rich adder
#

the whole component is moving collider

#

collision is what its meant for

rich adder
#

CC just makes so when you do move an object its with Physics aka collisions

#

As I mentioned when you switch to disabled you can freely move the object without CC

#

you just need to account for collisions yourself on edge for example

#

hence the suggested Raycasting for such detections.
if(leftSideRaycast) // if hit a wall
{dont move this way} etc.

surreal minnow
#

Yeah I know. You are right and that it is a possible way. I am just debating if there are any future cases where it could screw me over

small dagger
#

Is setting a collider to be a trigger the only way to detect if it collides with something without interacting with physics?

polar acorn
#

That's basically the definition of a trigger

small dagger
#

yeah it's not really a big problem for me, I just have a swtich-case statement in my "oncollisionenter" method and I just wanted to see if I could sneak the pickup in there

#

but I guess I will just have to settle for putting it in ontriggerenter

rich adder
rich adder
surreal minnow
fallen jacinth
#

yes my first code in C++ works!!!

polar acorn
#

Unity uses C#

rich adder
#

you might want to use the language unity api supports.. c#

grand badger
rich adder
#

You do realize without C++ you wouldn't have Unity

#

or many other apps

fallen jacinth
#

Then i will learn C#

acoustic nest
rough timber
#

Hello,
I don't understand why my UI is in 3D notlikethis
-# Help me pleasee

naive pawn
#

doesn't look like it

#

what's the actual issue here?

polar acorn
#

Seems like a normal canvas

rough timber
fallen jacinth
#

I tried 5 Times reinstalling hub

rough timber
keen dew
#

It'll look normal in the game. Open the game tab if you want to see it how it looks like in the game

polar acorn
rough timber
keen dew
#

no it's not

naive pawn
rough timber
#

oh sorry

polar acorn
rough timber
#

I thought there was a problem

polar acorn
#

Your screenshot looks like 2D to me

rough timber
#

okay

#

thanks

frigid sequoia
#

Is there a way to tell if a component is missing?

naive pawn
#

from what context?

frigid sequoia
#

Like players have X script as target, but it was destroyed and it's now missing, that's not really null, how can I tell that it's misssing?

naive pawn
#

it'll say it's missing in the inspector

frigid sequoia
#

Yeah, I want to tell the scrip that if that happens, set it to null instead

swift elbow
#

what's stopping you from just checking if the class reference exists or not?

frigid sequoia
#

Exists?

swift elbow
#

use an == null check

grand badger
#

they're looking for an editor script, guys

swift elbow
#

yeah would == null not override?

grand badger
#

Daleo you need an editor script for sure. I'm not sure the exact code atm (no time, sry)

frigid sequoia
#

Pretty sure "missing" is not = "null"

rich adder
#

most likely youre starting the coroutine more than once

red igloo
rich adder
# red igloo I will look into this thanks

You can use a bool to avoid start a new one unless bool is true, or store the Coroutine in vairable and set to Null when coroutine is done.
Most often I use variable
private Coroutine myRoutine
myRoutine = StartCoroutine(TheRoutine())
if(myRoutine != null) //stuff

#

StopCoroutine(myRoutine) or avoid StartCoroutine while its finishing

acoustic nest
grand badger
#

What’s the expected behaviour (vid)?

red igloo
grand badger
fleet venture
#

whenever i try to build my project i get these errors

#

it works fine when i just run it in the editor

red igloo
polar acorn
hollow wraith
#

How am I meant to alter the color of a sprite through code?
Can't figure out what is meant to be targeted in order to change the color of a sprite

fleet venture
hollow wraith
# polar acorn `.color`

And what am I meant to feed that?
I tried giving it an RGB and a HEX value and it didn't work

fleet venture
#

i need to do it based on name

fleet venture
#

not sure if there is an alternative

polar acorn
fleet venture
#

that cant be rigth

polar acorn
fleet venture
#

wdym

polar acorn
#

While the game is running

fleet venture
#

well ye

polar acorn
#

How do you intend to make a playable game if you have to drag in references while it's running 🤔

fleet venture
#

no

#

you dont drag them while playing

#

sorry misunderstanding

#

the dragging isnt at runtime

#

the usage of the prefabs IS at runtime

polar acorn
#

So then it doesn't need to be included in the build

#

It's an editor script

fleet venture
#

what no its not

#

ok

#

you dont have to drag references while its running

#

but i need to get a prefab based on a name

polar acorn
#

Right, so you don't need to include it

fleet venture
#

for loading/saving purposes

polar acorn
#

Put it in an Editor folder or exclude it from your assembly definitions if you have them

red igloo
grand badger
fleet venture
#

im trying to use Resources.Load now

polar acorn
fleet venture
#

its a runtime script

#

i think you misunderstood what i meant

#

i have a save, that stores a prefab id, i want to create a new instance of a prefab based on the id

#

so the id is the name of the prefab

#

rn i use the AssetDatabase to get the prefab dynamically to instantiate it

polar acorn
#

If it can be circumvented by dragging in a bunch of prefabs outside of runtime, it almost certainly can be an editor script

fleet venture
#

i dont get what an editor script would do

polar acorn
#

Assign the prefabs for you

#

So you don't have to drag them in

fleet venture
#

i have no idea how i would make that

#

cant i just do this dynamically?

#

why does it have to be hardcoded 💀

polar acorn
fleet venture
#

var guid = AssetDatabase.FindAssets(prop.prefabId.Replace("(Clone)", ""), new[] {"Assets/Prefabs"}).FirstOrDefault();

#

and then i

#

var propObject = Instantiate(AssetDatabase.LoadAssetAtPath<GameObject>(AssetDatabase.GUIDToAssetPath(guid)), new Vector3(prop.posX, prop.posY, 100), quaternion.Euler(0, 0, prop.rotation));

polar acorn
#

So, you know how to load a prefab by name.

You can set variables of scene objects outside of play mode using an editor script

fleet venture
#

im not entirely sure what you mean sorry

#

what i would do is like, create a dictionary with strings as keys and gameobjects as values

#

but idk how i would fill it

hollow wraith
# polar acorn a `Color`

Am I doing something wrong?
I've made sure everything that could be wrong is right but I still can't get the sprite to change colour

polar acorn
fleet venture
#

dictionaries dont even work well with unity

polar acorn
fleet venture
hollow wraith
polar acorn
#

so it automates dragging in

fleet venture
#

you can do that?

polar acorn
#

Yes, like I said, an editor script can set variables on objects in the scene

fleet venture
#

okay i understand

#

ye that would be better than dragging

fleet venture
#

cuz normally a dictoinary doesnt work with dragging

polar acorn
#

You could make a serializable extension of a Dictionary that'd get saved, but the built-in C# dictionary is not

fleet venture
#

ok im not doing that

#

i still hate that its not serializable

#

a dictionary is so basic

fleet venture
#

i cant rly find it when searching for editor scripting

rich adder
#

since you can use anything as a key

polar acorn
fleet venture
#

editorscript

#

like for how to assing the variables

#

and for where to put the script and stuff

polar acorn
#

Then you'd execute the function by selecting it from the top bar

fleet venture
#

it says not to use that

#

lol

polar acorn
rich adder
#

its fine for now(IMGUI) but yeah just kinda dropped that without contex mb

polar acorn
fleet venture
#

ah

rich adder
#

but yeah for future reference, Unity DOES want you to merge everything into UIToolkit eventually but thats another topic 😅

#

nothing wrong with IMGUI if you ever need some quick editor magic

fleet venture
#

the menu itme thing is to create new stuff?

rich adder
#

yea you can run function easily from right click

#

or the toolbar in this case

fleet venture
#

i want to add stuff tho

rich adder
#

what is "stuff"

fleet venture
#

oh wait i use FindObjectsOfType

rich adder
#

what do you want to add

fleet venture
#

the prefabs to the variables and strings

#

i use FindObjectsOfType for that?

rich adder
#

sure if you want to

#

its grabs them into an array

#

in editor those functions have no impact on gameplay anyway
(in game ofc u dont want to run that in update)

fleet venture
#

where is taht in

#

oh this should still be a monobehaviour?

#

uh it does say deprecated

rich adder
#

FindObjectsOfType is a static function

fleet venture
#

ah by type ofc

rich adder
#

unity switched up some functions in unity 6

fleet venture
#

i want the sorting order to be from top to bottom tho but thats not an option

#

im not sure how they are sorted in the editor

rich adder
#

alphabetically

fleet venture
#

oh

#

okay so next question, how do i then get the object in the scene?

rich adder
#

do you have some sort of identifier ?

#

to grab it

fleet venture
#

well its the only one of that type

#

so if i can do something similar to FindObjectsByType but for in teh scene

rich adder
#

oh its part of the scene already or you want to spawn it ?

#

Im confused on what you're going for I kinda just butted in at the end 😅

fleet venture
#

i want to link a prefab in assets, to a script variable in the scene

#

or well i want to link 200+ prefabs

rich adder
#

and you cannot use SerializeField why ?

fleet venture
#

i dont want to drag 200+ prefabs

#

i was told i can get unity to put them in for me with an editor script

#

so i dont have to drag

rich adder
#

ohh so you wanted a function to run in editor to do that/

fleet venture
#

yes

#

but ive never wrote an editor script so i dont really know what i am doing

rich adder
#

editor part is not important, its more important is how you want to grab/distinguish between these

#

eg if all Furniture had a Furniture component its a lot easier

fleet venture
#

i want to get all of these

#

all the prefabs have a Prop script

rich adder
#

I get that

fleet venture
#

ONLY the prefabs have that script

rich adder
#

but whats on the prefabs

fleet venture
#

Prop script

rich adder
#

so then FindObjectsOfType<Prop>()

fleet venture
#

ye i have that part down

#

but how do i get the object in the scene and how do i put it in the variable of said object

rich adder
#

place them in categories so they are easy to grab

#

say you want to place all barrels you could store them in List<Prop>barrells

#

perhaps here it would be okay to check their name

fleet venture
#

yes thats what i want to do but how do i store them

#

i have a List<gameobject> and a List<string>

#

the strings will be names

#

its basically key value

rich adder
#

why two lists

fleet venture
#

because a dictionary is not supported

#

sadly

rich adder
#

it is

#

just not serialized in editor

fleet venture
#

i dont want to make my own

#

oh wait so i CAN do a dictionary?

rich adder
#

ofc

fleet venture
#

i would much rather do that

#

its way cleaner

rich adder
#

you just cant see it in the inspector

naive pawn
#

there is a premade serializeddictionary package