#💻┃code-beginner

1 messages · Page 566 of 1

obsidian plaza
#

do you have any code for movement right now?

copper kettle
#

No, nothing seemed to work

obsidian plaza
#

probably

#

unless ur game is a top down rpg or something

copper kettle
#

It's a frogger

obsidian plaza
#

oh ok

#

wait how does that play

#

do u move a set distance

#

every press

copper kettle
#

Yes, 1 tile

obsidian plaza
#

gotchu

#

so you already know how to increase the position

#

in a script on the character, you need to check if the player is pressing anything

#

you need to do this every frame

#

so inside the script, you need to work inside void Update

copper kettle
#

Also, will something be different if it's touchscreen?

obsidian plaza
#

which goes executes every frame by default

#

well yea you would need on-screen controls

#

dont need to worry abt that rn

#

inside update you can check

if (Input.GetKeyDown(KeyCode.W))

#

then you change the position as you know

#

but honestly i think theres probably a way to move a set tile instead of moving a random position that you add

#

so could probably look a tutorial for that but this is the idea of what u wanna do

copper kettle
#

I found a lot of tutorials, but none with touchscreen

obsidian plaza
#

touchscreen is just using all ur same code but with different inputs, it shouldnt be that hard

#

if you are just starting out, why are you worried about touchscreen specifically

#

if its frogger

#

its just direction movement

gloomy cosmos
#

I'm trying to create a (terrible) C# Script system (I previously used Lua, but it was too slow). Basically I need a field in the inspector into which I can drag in a C# file. This file will have a single class extending a base class and I wanna create an instance of BaseClass using the class inside this file. I hope this explanation is understandable enough

#

A work around solution I came up with is to create a giant enum where each value represents each class, but it quickly gets cumbersome updating that, so hoping for an easier solution

obsidian plaza
obsidian plaza
gloomy cosmos
#

Previously this behaviour was stored in Lua scripts, but having 10k Lua interpreters running destroys fps surprisingly much

runic lance
#

can't you use scriptable objects for this?

gloomy cosmos
runic lance
#

yes

gloomy cosmos
#

oh wait, you mean like a class that extends ScriptableObject?

#

thats actually pretty genius

#

although don't Scriptable Objects share data? I'd need to potentially create thousands of instances of the class, and they'd need their own parameters to not mess with each other

runic lance
#

yeah, if you intend to store data in them, then every usage should be a new instance

#

this shouldn't be an issue though, you would probably need to store this data somewhere anyway

teal viper
olive galleon
#

How would I implement an attackCoolDown function for when an enemy damages the player? Here is my code:

gloomy cosmos
teal viper
gloomy cosmos
#

I meant like parameters that might change during runtime

teal viper
gloomy cosmos
#

A dynamic storage system is too fancy a term, what I mean is for example a set of dictionaries with string keys and various values, like floats, ints, vectors, and the bullet script can update data in the dictionary via the key

teal viper
gloomy cosmos
#

well for example you might wanna make a simple bullet which moves but also oscillates with a sine wave. Maybe you wanna make a pattern where there's a grid of bullets and one moves causing bullets in the grid to accelerate away from it, or a pattern where the bullets can stop, change orientation and continue moving, etc etc

teal viper
#

That's where composition comes to the rescue. You can have separate behaviors for bullet movement, rotation, effects, etc... And these behaviors can further be broken down into more basic components.

#

For example, you could have a base movement behaviour that just moves the bullet forward over time. And then extra behaviors that apply additional effect to the movement, like adding offset based on the sine wave.

gloomy cosmos
teal viper
#

I don't see any problem with using a state machine. Though it depends what exactly you're doing.

#

Like, what states do even bullets have? Flying and not flying?

runic lance
#

I mean, if the current architecture is not following composition it could be a huge undertaking
I really think the simplest solution would be to inherit from ScriptableObject and then create a new instance for each usage
if for some reason you're against mutable SOs you could probably use prefabs as well

#

then every different bullet behaviour would have its own SO and it would be easily swappable

gloomy cosmos
#

The states are basically an interface with 3 functions, on state enter, update and exit. These functions can be defined as anything, so yes flying and not flying is possible. This is useful if you wanna make bullets that can switch between complex behaviours based on timers or other parameters

teal viper
gloomy cosmos
#

I guess I will research how to do that, although it's hard to imagine right now

gloomy cosmos
#

Like a collection of classes which extend some interface and bullet scripts can have a list of "processing" interfaces that help with position calculation?

lethal raven
#

hello, does someone can tell me what kind of file this is ?

keen dew
#

ScriptableObject

lethal raven
#

thanks , what's the diff between this and a c#script ? and why use it ?

burnt vapor
#

Sounds like lack of experience tbh

#

Value types are immutable as they are passed by value. Modifying the property directly is impossible since you get a vlaue type when you access it, so it points nowhere. That's why you first get the value, modify it, then reassign it

#

You can call methods like Normalize() since they modify the actual struct rather than getting a copy

wintry quarry
lethal raven
#

so i beforehand create my script , then create a scriptableobject of it ?

#

sry i'm new to dev , i'm an artist and i want to continue a project that i was doing with a dev friend, sadly he left the project so i try to continue it

obsidian plaza
wintry quarry
obsidian plaza
#

u can do position += new vector3

craggy slate
#

whats the best way to learn coding?

burnt vapor
craggy slate
#

yt or

bitter apex
#

that's subjective

grand snow
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

burnt vapor
craggy slate
#

okay

teal viper
copper kettle
#

Why can't I change the maxTerrainCount in unity?

gloomy cosmos
copper kettle
#

yeah

bitter apex
#

Is there any way to use Resources.Load() outside of Awake() or Start()? Or is there something I can use as an alternative?

visual linden
rough bough
#

Could it be that it is private?

frail hawk
#

must be some errors

echo kite
#
    void DetermineRecoil()
    {
        transform.localPosition -= Vector3.forward * 0.1f;
        
        if (randomizeRecoil)
        {
            float xRecoil = Random.Range(-randomRecoilConstraints.x, randomRecoilConstraints.x);
            float yRecoil = Random.Range(-randomRecoilConstraints.y, randomRecoilConstraints.y);

            Vector2 recoil = new Vector2(xRecoil, yRecoil);

            _currentRotation += recoil;

        }
        else 
        {
            int currentStep = clipSize + 1 - _currentAmmoInClip;
            currentStep = MathF.Clamp(currentStep, 0, recoilPattern.Length - 1);

            _currentRotation += recoilPattern[currentStep];
        }
    }

how do i fix red lines and how do i add weapon sway

copper kettle
#

Console shows nothing and I already tried to make it public

visual linden
polar acorn
teal viper
polar acorn
final gazelle
visual linden
#

Wait, is there a class called MathF too...

#

Anyway, should be Mathf, I'm pretty sure.

final gazelle
# echo kite

well then you assigning the wrong data type ornot assinging it properly

polar acorn
visual linden
#

_CurrentRotation, capital C

polar acorn
echo kite
#

oh

#

what about random

visual linden
wintry quarry
bitter apex
#

I thought it was an issue with the main class but it wasn't 😢

visual linden
# echo kite

The actual Hint in this screenshot even explains the issue and how to fix it... Facepalm

echo kite
#

it doesnt work

#

it stopped shooting and it gave me this error

swift elbow
visual linden
#

You probably want to stop what you're doing and find a good introductory tutorial or course for C# (Check out Mosh' course on Youtube).
There's not enough hand-holding in the world we can do that will help you advance with your project if you don't know the super basics of programming.

swift elbow
#

jinx lol

echo kite
#

i cant leave this project like that

#

i will do that after this

swift elbow
#

it'll only take like a week...

echo kite
warm crater
#

What's a good tutorial?

echo kite
#

so how do i fix that error

final gazelle
#

!code

eternal falconBOT
frail hawk
#

sani needs spoonfeeding that is it

swift elbow
warm crater
echo kite
polar acorn
final gazelle
swift elbow
visual linden
# echo kite ur in a code-beginner

I agree, you should be able to ask your questions :) You don't know what you don't know.
But in this case, you're not aware of just how much of the pure basics you're lacking- So our answer to you will inevitably be that you need to read up more on C# and programming fundamentals.

#

We can't code your project for you.

visual linden
polar acorn
swift elbow
# echo kite i dont have week

we're saving you a lot of time right now by not just spoon feeding you answers. it'll take you more than a week to finish what youre trying to do now than to learn c# basics

warm crater
swift elbow
# warm crater This?

no, just a c# tutorial first is what you need. then you can go into unity stuff

visual linden
swift elbow
#

free code camp has a 4hr c# tutorial

warm crater
#

Oh

#

Yeah I see now

echo kite
swift elbow
polar acorn
visual linden
final gazelle
warm crater
eager spindle
#

arrays don't even take that long to learn

echo kite
polar acorn
eager spindle
#

you can double click an error and it opens up in your editor

swift elbow
visual linden
# echo kite i will learn after it

After this error, there will be another error, just as the 3 errors before it we already helped you fix.
At some point, helping you is just us doing your work for you, and your insisting on us doing it is a bit.. Impolite, let's say.
Take your time to learn programming instead, or give up. Those are your options.

eager spindle
swift elbow
visual linden
final gazelle
polar acorn
polar acorn
visual linden
# echo kite

This is all valid code. You're just showing us you don't even know how to find the line where the error is occurring.

polar acorn
copper kettle
#

Why doesn't maxTerrainCount appear in inspector? I'm following a tutorial

echo kite
polar acorn
polar acorn
echo kite
eager spindle
#

it's case sensitive

echo kite
eager spindle
#

is it corrected now?

echo kite
#

yes

polar acorn
copper kettle
#

Tbh, I don't even know what that means

echo kite
#

i fixed those errors but new error came up

eager spindle
#

what's the current error

echo kite
eager spindle
frail hawk
polar acorn
# echo kite

You have already been told what this one is. You're trying to access an index of an array that is outside the bounds of the array. You can't get the sixth element from a list with five things in it

echo kite
torpid igloo
#

Hi, I followed the 3d platformer controller tutorial by the "Dave / GameDevelopment" youtube channel, and i want to add a way to jump multiple time in the air until the amount of jumps that you already did is less or equal to a "maxJumps" variable. how can i do this?
this is my code:
https://www.codebin.cc/code/cm5l4xtup0001mv03bx69utjo:EH85KYr7o8pQPDH3MbwcGEKujpo9UA8LuHPXD4WDkWzP

eager spindle
# echo kite

do you know how to use the debugger in the ide

#

put a breakpoint at like line 90

#

look at currentStep

visual linden
# echo kite

recoilPattern is an array, and currentStep is an index of that array. If the index is higher or lower (outside the bounds), an exception will be thrown because you can't access anything with an invalid index.

eager spindle
#

make sure currentStep isn't more than the length of recoilPattern

eager spindle
# echo kite

also, just to be sure, describe to me what line 90 does

copper kettle
fickle plume
eager spindle
#

you click big green button, put a breakpoint on line 90, then run the game

#

the game will stop when it hits said breakpoint

#

in your unty project it'll prompt you to turn on debug mode, enable it

copper kettle
fickle plume
eager spindle
#

do you even know what the code does

torpid igloo
#

yeah i know

#

but how do i combine this part of code(the one that makes the player jump) with your suggestion? when do i check if the player is grounded?
this is the code:

if (Input.GetKey(jumpKey) && readyToJump && grounded)
        {
            readyToJump = false;
            Jump();
            Invoke(nameof(ResetJump), jumpCooldown);
        }
frail hawk
#

if you want multiple jumps you would need to remove the grounded bool or change it in a another way

eager spindle
#

under the Jumping header add an integer for number of jumps
in this if condition you can check if the number of jumps ++ is less than the max number of jumps
in resetjump you can set number of jumps back to the default value

#

we can't spoon-feed you code but this is how it's done

torpid igloo
#

the grounded bool is set to this:
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);

frail hawk
#

yeah it is checking for the ground so you are only able to jump when you are grounded which is not what you want. you have to edit a few steps

eager spindle
#

when you are grounded, reset the number of jumps to the max number of jumps
when you attempt to jump, if there's ≥1 jump, consume 1 jump to Jump()

torpid igloo
#

thank you it works now. i needed to do some MAJOR changes to make it work

quick fractal
#

This is a very basic question but I can't find much in the way of documentation with Mathf.Lerp; If I were to use it to say, lerp an animator's speed over the span of a second, would I do A or B?
animator.speed = animator.speed * Mathf.Lerp(animator.speed, newValue, 1);
animator.speed = Mathf.Lerp(animator.speed, newValue, 1).

swift crag
#

All that Lerp does is give you a value somewhere between two other values

#

That's it. It doesn't do anything "over time"

#

Mathf.Lerp(foo, bar, 1) returns bar

#

because you asked for a value 100% of the way from foo to bar

#

That is all it does, ever.

rough lynx
#

Beat me to literally every point I was gonna make lmao

swift crag
#

If you want something to change over time, you need to repeatedly set the value (perhaps in a coroutine)

quick fractal
#

I was considering throwing it in a while loop

swift crag
#
IEnumerator ChangeSpeed(Animator animator, float target) {
  float start = animator.speed;
  float t = 0;

  while (t < 1) {
    animator.speed = Mathf.Lerp(start, target, t);
    t += Time.deltaTime;
    yield return null;
  }
}

e.g.

#

actually, this has an error

#

On the last step, when t equals or exceeds 1, we exit the loop

#

the animator's speed never actually reaches target

#

This could be corrected by adding animator.speed = target; after the loop.

#

It's very important to grasp that there is no "magic" in any of the Mathf methods. All they do is compute a value given some inputs.

rough lynx
quick fractal
swift crag
#

+= is not the "subscribe" operator

#

that is one way that it is used, yes

#

It's properly called the addition assignment operator

#

here, it's equivalent to

#

t = t + Time.deltaTime;

quick fractal
#

Learn something new every day 😁
Thank you, I think Mathf makes a ton more sense now

swift crag
#

+= and -= are commonly used with event members because you aren't actually allowed to directly assign to them

#

Otherwise, you could absolutely do

#
Something.OnEvent = Something.OnEvent + MyCallback;
#

(that's what actually happens internally)

quick fractal
grand snow
#

fun fact, you can override the add and remove functions for events (kinda like properties!)

swift crag
#

yeah, you can define custom accessors, just like you can for properties

#

you just rarely need to

grand snow
#

yea ive never done it myself but im sure it has a use

hidden bone
#

I've got a pretty fresh Unity scene open and I have both a first person controller and a Cinemachine camera set up. In the inspector, Cinemachine allows one to both track a gameobject and set up input axis controls (mouse).
I want the player to rotate with the Cinemachine camera but I do not know how to do so. What can I do?

fresh arrow
#

in this code i dont understand that if the rigidbody.linearVelocity is also the target velocity (in the SmoothDamp) why do we have to write both of them in the smooth damp

wintry quarry
#

Target velocity is a different variable entirely

#

You need to provide the current velocity so smooth damp can calculate the new velocity for this frame based on it

#

Of course, right now you're not using the result at all so it won't do anything

fresh arrow
#

if i move the player it is because of the target velocity but the character wont actually move if i dont declare the ribidybody.velocity being equal to target velocity

#

forget the damping for now

wintry quarry
fresh arrow
#

hence they both are the same

#

then why in smooth damp we add both of them

#

or i am understanding it wrong

wintry quarry
#

If you want to just completely overwrite the velocity and ignore the previous velocity, you can of course set it to whatever you want

fresh arrow
#

but targetvelocity and rigidbody.velocity are the same where is the previous velocity?

wintry quarry
#

They aren't the same

#

Why are you thinking they're the same

wintry quarry
#

RB.velocity is your current velocity

#

Target velocity is the velocity you want to be going

#

Smooth damp will calculate a new one in between to make it smooth

fresh arrow
#

alright

#

but we add a current velocity ref in the smooth damp

#

what about that?

wintry quarry
#

That's for "how fast the velocity is changing"

#

The fact is smoothdamp is just a math function

#

It has no idea that the thing you are damping is a velocity

#

Normally it's a position

fresh arrow
#

much appreciated

#

thanks

ebon fog
#

Hi everyone, i been looking for a tutorial on how to make multiplayer fps for a basis of my game, so i could build atop of it. But there is many of them and i don't know which one is the way to go today. Also i want to do this as my uni project, as i lost my will to programing, but if i to do something it will be a game. So is there some guide or specific tech you can recommend?

trail gulch
#

hi guys and happy new year
can someone explain why the hit.point is keep changing even if the mouse stay still, im receiving a diffent values that the last one logged.
i have this cript attached to a sphere and it keep jumping back and forth

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

public class Brush : MonoBehaviour
{
    
    public float sizeChangeSpeed = 0.1f; 
    public float minSize = 0.1f;         
    public float maxSize = 5f;
    

    void Update()
    {
        MoveBrush(); 
        ChangeBrushSize(); 
    }

    private void MoveBrush() 
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, Mathf.Infinity) && Input.GetMouseButton(0))
        {
            Debug.Log(hit.point);
            transform.position = hit.point;
        }

    }

    private void ChangeBrushSize() 
    {
        float scrollInput = Input.GetAxis("Mouse ScrollWheel");
        if (scrollInput != 0)
        {
            // Increase or decrease the size of the sphere
            float newScale = Mathf.Clamp(transform.localScale.x + scrollInput * sizeChangeSpeed, minSize, maxSize);
            transform.localScale = new Vector3(newScale, newScale, newScale);
        }
    }
}


rich adder
#

and you're calling it every frame running it before mouseheld

trail gulch
#

another collider?

rich adder
#

you can log hit.collider.name

trail gulch
#

lolis hiting itself

rich adder
#

use layers then

#

ignore its own collider

trail gulch
#

yeah thanks

#

i did this

if (!hit.transform.CompareTag("Brush"))

but now is moving very slow, like it glitching

rich adder
#

idk what you mean "moving slow" how would this at all affect movement

trail gulch
#

no, i mean the movement it glithchy
when i move the mouse, the position of the spere is snaped, not smoothing like when the mouse position is

rich adder
trail gulch
#

i removed this part

&& Input.GetMouseButton(0))
#

now is folowing the mouse

rich adder
#

are you raycasting onto a plane collider ?

trail gulch
#

no, a mesh collider

rich adder
#

so the brush also has a collider?

#

why

trail gulch
#

i need it later, for collision, for getting the contacts

rich adder
#

so why dont you just put what ray supposed to hit in terms of LayerMaskk

#

so it doesnt even hit it in the first place

trail gulch
#

i didnt try it, but ill check it out
this LayerMask thing is new to me

rich adder
slow mantle
#

guys I'm trying to make my second game but me and my galaxy brain galaxybrain decided it would be a good idea to make it be a multiplayer one. Is this a bad idea?

rich adder
#

yes

#

bad idea

#

second "game" is just not enough. Is your first game a published fully polished single player game ?

#

or just a learning project / game.

#

there are soo many systems and concepts that multiplayer needs, you're gonna not have a good time learning it tbh. You can try though small bits a time to get a test to see if you don't believe me lol

flat crystal
#

can anyone tell me why unity is saying "IndexOutOfRangeException: Index was outside the bounds of the array.
GameManager.Start ()"

rich adder
#

the whole method is full of possible

#

probably GreenGem is empty/ doesnt have anything in it

warm crater
#

Can someone tell me why my movement is like this?

#

It freaks out when I don't move

flat crystal
polar acorn
rich adder
swift crag
#

The preview values you see in the animator window can be...weird

#

I get NaNs in there all of the time while outside of play mode

swift crag
#

4.5 * 10^-20 is very close to zero

rich adder
# slow mantle I'm a bit ambitious, yes...

you can try it though just to see what its like, but honestly 2nd game just isn't enough. You should probably have many many project types , but again doesn't hurt to try / see what its all about.

slow mantle
rich adder
#

just different types of projects, games and apps, anything in between

slow mantle
#

heard all about learning how to make a multiplayer game, heard it's just actual evil lol

rich adder
#

I dont always make a game in unity, sometimes just work on a specific mechanic or feature

slow mantle
#

"It can't be that bad" is my thought

rich adder
slow mantle
#

(It probably is that bad)

rich adder
#

the most basics suggestion for you to learn I can say is, forget the Easy Transform Sync that netcode component takes care for you.. Thats too easy..
Instead, try to sync up the same values between clients and server, or do simple sync stuff on your own like that

#

RPCS

#

hell even NetworkVariables feel like cheating.. It does all the sync for you

#

Netcode did make it a bit easier tbh

slow mantle
#

I'll keep that in mind
Yeah my problem is, I've never actually been that good at programming, more on the creative side, can't exactly hire somebody else either, so I'm stuck with learning it. Been fun though! It makes me think

rich adder
# slow mantle I'll keep that in mind Yeah my problem is, I've never actually been that good a...

yeah it can get confusing, just think of it more as a tool you use for logic rather than some memorizing or skilled trait.. or some sort of talent.. anyone can get good at it just like any other tool, the more you utilize it less intimidating it is.

I used to use Game Maker n such platform that only allowed me Drag And Drop logic mainly, was always intimidated of code lol hated GML was "Scary looking"
Here I am 5 years later writing tons of code in c# instead lol

#

if its not code relevant why did you post it here 🤔

arctic shore
rich adder
arctic shore
#

yes its in image component

rich adder
#

oh right

rich adder
dapper mirage
#

Can someone please help me understand why the section for wall jumping never happens? The checks for isTouchingWall and isInAir are correct but even when both are true it only ever uses normal jump

{
    if (isTouchingWall && isInAir)
    {
        //Wall jump logic: Add horizontal force away from the wall
        Debug.Log("Wall jump");
        Vector2 wallJumpDirection = new Vector2(0, 0);

        if (BounceLeft())
        {
            wallJumpDirection = Vector2.right;
        }
        else if (BounceRight())
        {
            wallJumpDirection = Vector2.left;
        }
        rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpStrength);
        rb.AddForce(wallJumpDirection * wallBounceForce, ForceMode2D.Impulse); 
    }
    else if (!isInAir)
    {
        //Normal jump
        Debug.Log("Normal jump");
        rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpStrength);
    }

    isInAir = true; //Prevent further jumping until grounded or touching a wall
}```
wintry quarry
#

you are suggesting that if is broken

#

it isn't

dapper mirage
#

I understand that

wintry quarry
#

Add some more Debug.Log lines and see what's going on

#
Debug.Log($"In air? {isInAir}, touching wall? {isTouchingWall}");```
dapper mirage
#

It was my mistake 🤦‍♂️
if (!isInAir && (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W)))

#

But now I have a new issue, it wont add the impulse to the player in the opposite direection of the wall

wintry quarry
#

Sounds like a problem with the logic for picking the direction

dapper mirage
#

What im trying to do is check what side of my character the wall is, so BounceRight() checks for if the wall is on my right
if thats true, wallJumpDirection is set to left and then that is multiplied by wallBounceStrength when I use AddForce()

{
    wallJumpDirection = Vector2.left;
}
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpStrength);
rb.AddForce(wallJumpDirection * wallBounceForce, ForceMode2D.Impulse); ```
#

As far as I can tell the logic is sound but Im worried that Im using AddForce wrong

wintry quarry
#

Where is this code all running?

#

And what does BounceRight and Left do?

#

And what if neither one is true?

dapper mirage
#
{
    return Physics2D.OverlapCircle(rightWallcheck.position, WallCheckRadius, wallLayer);
}

it is an empty child object to the right of the player

#

I know its functioning properly because I set isTouchingWall to public so I can see it in the editor when running the game

wintry quarry
#

watching the inspector is sometimes convenient but it isn't a true test for how the code is behaving

#

Som,ething like:

        if (BounceLeft())
        {
            wallJumpDirection = Vector2.right;
            Debug.Log("Detected a wall to the left. Bouncing right");
        }
        else if (BounceRight())
        {
            wallJumpDirection = Vector2.left;
            Debug.Log("Detected a wall to the right. Bouncing left");
        }``` would be nice
#

And then logging:

Debug.Log($"Adding wall jump force: {wallJumpDirection * wallBounceForce}");```
#

would complete the picture and you can see if your logic is working properly.

cerulean badger
#

Why is my zone trigger script not working? It doesn't have any errors.

wintry quarry
wintry quarry
#

assuming you tried to jump off a wall that's on the left of your player?

dapper mirage
#

Yes

wintry quarry
#

so then if you have a problem it's elsewhere

#

what's the issue exactly?

#

Also looks like it's definitely happening

#

which contradicts what you originally said "it never happens"

#

What made you say that?

dapper mirage
#

Force is applied upwards correctly but player doesnt get pushed away from the wall

#

my original issue was different

wintry quarry
#

maybe you aren't applying enough force?

#

How much mass does the player have and how big is it?

dapper mirage
#

It was because the check for if the player was pressing space was also checking for isInAir which was redundant and preventing the code from running at all

wintry quarry
#

Also you might already have a bunch of leftward velocity

#

so adding a force to the right might not be enough to cancel it out unless you add quite a lot

dapper mirage
#

Setting wallbounceforce to a rediculous number doesnt do anything

wintry quarry
#

TO make this more consistent you might consider just setting the verlocity directly like you are doing for the vertical

wintry quarry
#

does your movement code perhaps set the horizontal velocity directly?

dapper mirage
#

rb.linearVelocity = new Vector2(move * speed, rb.linearVelocity.y);

wintry quarry
#

yep

#

See how that would break it?

#

you're overwriting it

dapper mirage
#

Yeah I see

#

How could I fix it?

wintry quarry
#
  • switch your normal movement to be additive/use forces as well
  • disable the normal movement code for some time after a side jump
#

something like one or both of those

dapper mirage
#

Is there any way you could help me make the timer for the disable movement?

#

I dont understand how they work and all I can find online is for making level timers and stuff

wintry quarry
#

could be done pretty easily with a coroutine, or just a simple float variable

#

timers are not complicated

dapper mirage
#

I have 2 variables:

public bool movementDisabled = false;```
cerulean badger
swift crag
#

the condition for player movement is now just Time.time >= 12

wintry quarry
cerulean badger
#

what should I write?

wintry quarry
#

OnTriggerEnter2D(Collider2D other)

#

for example

#

there are 2D versions of all those things

cerulean badger
#

oh got it

dapper mirage
swift crag
#

You can also just store the time that movement will be allowed at again

#
moveDisableTime = Time.time + 2f;
dapper mirage
#

Ohh I see now

#

Thats pretty cool

#

But wouldnt this be affected by framerate? Could I just use Deltatime.time in the same way?

frail hawk
#

i tested it out once it is pretty much the same. you can use delta time or Time.time

dapper mirage
#
{ 
    disableMovementStartTime = Time.time;
    movementDisabled = true;
}```
and at the top of the update nethod:
```if (Time.time >= disableMovementStartTime + disableMovementTime)
{
    movementDisabled = false;
}```
cerulean badger
#

im having difficulty on returning an object from the explorer via script. I've tried some methods like GameObject.Find but they don't work 100% of the time

wintry quarry
#

The best way to do this is a direct reference dragged and dropped in the inspector.

cerulean badger
#

wdym active object and inspector?

wintry quarry
eternal falconBOT
#

:teacher: Unity Learn ↗

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

cerulean badger
wintry quarry
#

not components

#

AudioSource is a component

#

it's irrelevant to our conversation

#

as is "with an audio file inserted in it"

#

To be perfectly honest is sounds to me like you're having some specific problem and you should ask about that problem

#

I suspect your GameObject.Find musings are not exactly related.

#

Show us what you're trying to do and what's going wrong

#

and we can help

cerulean badger
wintry quarry
#

explain it

#

and show what you tried

cerulean badger
#

i've never heard about inspector

wintry quarry
cerulean badger
#

and idk what being active does to an object and how do I deactivate it

wintry quarry
#

it's one of the most basic and fundamental parts of the editor

wintry quarry
cerulean badger
rich ice
# cerulean badger wdym active object and inspector?

definitely listen to what praetor said. but for context, the inspector is a window (you can see a windows name on the slightly darker bar above all the UI). whether or not an object is active is the little tick in the image.

wintry quarry
#

You can activate or deactivate objects either from the inspector or in code

rich ice
#

(i was super late on that guh)

cerulean badger
# wintry quarry What is your problem

i think my biggest issue is knowing the names from the stuff in unity. Y'see, I've migrated from roblox studio and there don't have a specific name for the inspector, it's just the properties tab

swift crag
#

yes, there will be different names over there

wintry quarry
swift crag
#

they're talking about the equivalent concept in Roblox Studio

wintry quarry
#

Yes, "The properties tab"

swift crag
#

oh, yes

#

true :p

cerulean badger
#

so an object comes active by default when u create it, right?

swift crag
#

That is true, yes.

cerulean badger
wintry quarry
#

Unity is made up of GameObjects with Components attached to them

rich ice
cerulean badger
wintry quarry
wintry quarry
#

AudioSource is a component that can be attached to any GameObject

swift crag
#

a "cube" is a game object with:

  • a MeshFilter, to hold a mesh
  • a MeshRenderer, to draw the mesh
  • a BoxCollider, to provide a physics shape
#

for example

#

You have a game object with:

  • an AudioSource, to play sounds
wintry quarry
#

GameObjects are generic. THey don't do anything themselves. There aren't different types of GameObject

swift crag
#

That's one very important thing to grasp

wintry quarry
#

there is only one type of GameObject - the differences come from which components are attached to them

swift crag
#

Unreal, for example, doesn't do this. You create different kinds of objects

#

in Unity, everything is a GameObject

cerulean badger
swift crag
#

"The component from anything"

rich ice
#

any object(i assume)

swift crag
#

"from" is the really confusing word here

wintry quarry
#

AudioSource IS a component. It is not "from" anything. It can be attached to any GameObject

cerulean badger
swift crag
#

here's a random object from my game: a Spectator

#

it has three components attached to it

echo ruin
#

Objects are the things in the hiearchy and components are the things in the objects (in the inspector menu)

swift crag
#

er, actually, it has four (:

#

Transform is also a component, after all

cerulean badger
#

ok, i think i got what I was looking for

rich ice
echo kite
#
    void DetermineRecoil()
    {
        transform.localPosition -= Vector3.forward * 0.1f;

        if (randomizeRecoil)
        {
            float xRecoil = UnityEngine.Random.Range(-randomRecoilConstraints.x, randomRecoilConstraints.x);
            float yRecoil = UnityEngine.Random.Range(-randomRecoilConstraints.y, randomRecoilConstraints.y);

            Vector2 recoil = new Vector2(xRecoil, yRecoil);
            _currentRotation += recoil;
        }
        else
        {
            if (recoilPattern == null || recoilPattern.Length == 0)
            {
                Debug.LogError("Recoil Pattern is null or empty!");
                return;
            }

            int currentStep = clipSize + 1 - _currentAmmoInClip;
            currentStep = Mathf.Clamp(currentStep, 0, recoilPattern.Length - 1);

            _currentRotation += recoilPattern[currentStep];
        }
    }

    IEnumerator ShootGun()
    {
        DetermineRecoil();
        StartCoroutine(MuzzleFlash());
        yield return new WaitForSeconds(fireRate);
        _canShoot = true;
    }

there are no errors but why does gun not have recoil

eternal falconBOT
echo kite
rich ice
trail gulch
#

what algorithm can i use for triangulation for a set o points in 3d that represents a surface?

echo kite
rich ice
neat oak
#

i want to ask something for example rn i'm learning c# it tried learning c++ about 2 years back i've only done stuff in a console, and followed one of brackeys game tutorials also 2 years ago but at the end i had a game and still no idea how to make one. Now I'm learning c# and I'm wondering how do i just do stuff in unity like for example I have never done anything like move something in a console code i wrote, how do i even begin to for example move a sprite.

rich ice
eternal falconBOT
#

:teacher: Unity Learn ↗

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

echo kite
rich adder
#

better to start with a structured course

rich ice
rich adder
#

youtube is only good when you get enough experience to recognize any mistakes and improve on them

languid spire
rich ice
eternal falconBOT
echo kite
languid spire
echo kite
#

when i asked how to make weapon sway

#

they told me i needed to separate movement from weapon

dapper mirage
#

I want to change this to additively change my horizontal velocity so it can still be affected by other forces
rb.linearVelocity = new Vector2(move * speed, rb.linearVelocity.y);
but when I write rb.linearVelocity += new Vector2((move * speed) -= rb.linearVelocity.x, 0); it doesnt run

echo kite
#

now i cant make weapon sway because weapon isnt player

rich ice
#

you'll have to do that on a seperate line

languid spire
dapper mirage
echo kite
#

i learn more from yt than doing it by myself

rich ice
languid spire
echo kite
#

@languid spire

#

look

#

this dude

#

learned for 2 years

rich ice
#

2 years back*

rich adder
#

also brackys, what did they learn really lol

rich ice
#

to be fair, i spent 4-ish (maybe 5 now) years learning off youtube

#

still suck at programming

#

but atleast now i can code lol

cerulean badger
#

a Transform value has the whole object as the value or only the name?

frail hawk
#

brackys made great unity tuts, even tho his coding skills were not perfect

echo kite
rich adder
echo kite
#

i would have left when i saw "private void"

echo kite
rich ice
#

!code

eternal falconBOT
echo kite
rich ice
#

yup

rich ice
frail hawk
#

sani do you have a camera lerp , i think it might fix your weapon sway issue

verbal dome
echo kite
#

also i literally dont have script for weapon sway

verbal dome
#

@trail gulch Like can the points form a sphere or something or is it always somewhat planar?

echo kite
#

i deleted those

verbal dome
echo kite
slender nymph
#

this appears to be a variable that isn't even used

verbal dome
#

Seems like not at all

slender nymph
#

this is assigning to it, not using its value

verbal dome
#

Sure, I see you are modifying it, but not using it

#

I would expect you to use it to rotate your weapon transform or something

echo kite
#

what do i need to do?

swift crag
#

do something with the variable, presumably

#
float whatever = 123;

this does not do anything on its own

#

You are calculating a recoil value, but you aren't actually using it to do anything

echo kite
#

guy in tutorial doesnt do it

swift crag
#

perhaps you need to keep watching...or perhaps you missed a step

slender nymph
#

link the tutorial

echo kite
swift crag
#

it is, indeed, used in the tutorial

#

see approx. 21 minutes

echo kite
swift crag
#

Yes, it's used for looking around

#

That's why it's called _currentRotation

echo kite
#

from weapon

swift crag
#

Yes, I think that's a good idea

#

I wouldn't want recoil to permanently change my view direction

verbal dome
#

(Some games do that)

swift crag
#

i've shot a rifle before without flying into the ceiling, somehow

#

So I think you want to be doing something like this

#
  • When you fire, add an offset to a "current recoil" variable
  • Slowly return that variable to zero
  • Add the "current recoil" variable to your "current rotation" variable when calculating a look direction
echo kite
#

yea but i have completly different script for player movement so how am i supposed to use currentrotation

verbal dome
#

Maybe show your scripts

echo kite
verbal dome
#

Looking at the tutorial, looks like the GunController script should rotate the root which is the player..?

#

The guncontroller should only modify the gun's local rotation IMO

#

Not rotate the whole player

swift crag
#

ah, that would make sense

echo kite
#

whole player rotates in playermovement

#

when u look around does your arms detach and rotate around you?

verbal dome
echo kite
#

yes in playermovement script

#

but it doesnt sway

#

and it doesnt recoil

verbal dome
#

Not sure why ApplyWeaponSway is in the player controller when you have a separate gun script. That's clearly where it belongs to

#

Oh so that's camera sway

echo kite
verbal dome
#

You need to use _currentRotation to rotate the gun

#

(Also can we please stop using pastebin, there's no syntax highlighting and it has ads)

dapper mirage
#
//Handle horizontal movement, disallow horizontal movement while movementDisabled variable == true
if ((Time.time >= disableMovementStartTime + disableMovementTime) && movementDisabled)
{
    movementDisabled = false;
    Debug.Log("movement enabled");
}
move = Input.GetAxis("Horizontal");
if (!movementDisabled && (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)))
{
    rb.linearVelocity += new Vector2((move * speed) - rb.linearVelocity.x, 0);
}```

//Handle jumping, disable horizontal movement for a short period of time after bouncing off wall
if (isTouchingWall && isInAir)
{
//Wall jump logic: Add horizontal force away from the wall
Debug.Log("Wall jump");
disableMovement();
Vector2 wallJumpDirection = new Vector2(0, 0);

if (BounceLeft())
{
    wallJumpDirection = Vector2.right;
    Debug.Log("Detected a wall to the left. Bouncing right");
}
else if (BounceRight())
{
    wallJumpDirection = Vector2.left;
    Debug.Log("Detected a wall to the right. Bouncing left");
}
Debug.Log($"Adding wall jump force: {wallJumpDirection * wallBounceForce}");
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpStrength);
rb.AddForce(wallJumpDirection * wallBounceForce, ForceMode2D.Impulse); 

}```

//Starts a timer that disables horizontal movement
private void disableMovement()
{
    Debug.Log("Movement disabled");
    disableMovementStartTime = Time.time;
    movementDisabled = true;
}```

Can someone please help me solve an issue where the player is able to wall jump without being pushed away if they hold the movement key in the direction of the wall?
rich ice
#

!code

eternal falconBOT
dapper mirage
#

mb

echo kite
verbal dome
#

I mean use one of the links in the bot message above^ instead of pastebin

verbal dome
dapper mirage
#

Sure 1 sec

verbal dome
#

And adding cs to the start of your inline code block will make it easier to read

echo kite
verbal dome
#

This has nothing to do with "looking around"

#

I mean it does but that's not the thing you should do here

echo kite
#

but not left and right

verbal dome
#

Idk what you did

echo kite
#

i wrote that whole thing

#

whatever transform localrotation is in

#

but i deleted

verbal dome
#

Yeah deleting the code that you need help with is a great idea

echo kite
#

i thought i needed to seperate looking around and gun

rich ice
dapper mirage
#

Player should not be able to climb the wall like that and should instead bounce off the wall when they try to jump on it like at the end

hexed terrace
#

you didn't include the code for BounceLeft() and BounceRight() ?

dapper mirage
#
    {
        return Physics2D.OverlapCircle(groundcheck.position, groundCheckRadius, groundLayer);
    }

    private bool BounceLeft() 
    {
        return Physics2D.OverlapCircle(leftWallcheck.position, WallCheckRadius, wallLayer);
    }

    private bool BounceRight()
    {
        return Physics2D.OverlapCircle(rightWallcheck.position, WallCheckRadius, wallLayer);
    }```
#

Where groundcheck and leftwallcheck/rightwallcheck are empty child objects of the character capsule

#

positioned to the left, right and bottom of it

verbal dome
#

I went over the code and to me it seems OK

dapper mirage
#

yes even setting wallBounceForce to something really high doesnt affect the issue

verbal dome
#

Does the "disable movement" part seem to work?

dapper mirage
#

It does

verbal dome
#

Does it ignore your input for a moment after you walljump?

#

Okay

ivory saffron
#

I did some changes to the script (renamed it, for one) and now it runs Awake() but nothing in Start() or Update(). i checked with debug logs. tried restarting unity and delete and import back the script.

wintry quarry
ivory saffron
#

the script is enabled

wintry quarry
#

if there's an exception in Awake, it will get disabled by Unity automatically

ivory saffron
#

how to check for exception?

wintry quarry
#

Look in the console window

ivory saffron
#

there's nothing

#

only the consequences of the script not working

wintry quarry
#

Such as?

#

Can you show us?

#

(the code, the logs, etc)

ivory bobcat
#

Can you show the logs?

ivory saffron
#

so this is the first one. the script not working is PlayerUnit

wintry quarry
ivory bobcat
#

There are errors?

wintry quarry
#

what script is that happening in, and on what line, etc.

#

But yeah it looks like there are errors

#

so that's the likely cause. If that's in Awake, it will disable the script

#

This is almost certianly a bad idea to do in Awake

#

referencing other singletons should happen only in Start or Update or something

#

because you don't know which Awake will run first

#

They can run in any order - .instance might not be ready yet.

ivory saffron
#

i will remember how exactly the dependencies work in a moment but for now, the reason i put it in awake is the order of execution. i think of UIinventory and inventory

wintry quarry
#

Order of execution is exactly why it won't work unless you're manually setting up the execution order in the Script Execution Order settings

#

which I wouldn't recommend

trail gulch
#

i want to trIangulaate the pink points

ivory saffron
#

maybe i had modified the execution order and then it reset after i renamed the script, that's probably the reason

wintry quarry
#

It's better to design your code to work with any execution order if you can get away with it

tender stag
#

i wouldnt need the first loop right?

wintry quarry
#

Basically those settings are super invisible and as you just saw - fragile to certain classes of code modification

tender stag
wintry quarry
#

I guess you're saying because of GetComponentsInChildren?

tender stag
ivory bobcat
tender stag
#

its still going to find all the renderers

wintry quarry
# tender stag yup

Yes especially with the way you wrote the GetComponentsInChildren, the outer loop is redundant

#

you will end up doing extra work this way

tender stag
swift crag
#

invisible dependencies are scary!

tender stag
swift crag
#

my game has some and it makes me unhappy

verbal dome
# trail gulch

Delaunay triangulation would probably work here. Just have to project the vertices onto Vector2's first, unless you find a 3D implementation

tender stag
#

for properties what is the c# naming conventions

#

like here

#

which one would be pascal case

#

i changed it to private btw

#

just realised

#

would the private one be camel or pascal?

swift crag
#

according to Microsoft, you're meant to PascalCase any public member

#

I generally do not do this

tender stag
#

i try to stick with it

swift crag
#

I camelCase fields and PascalCase properties.

tender stag
#

so according to microsoft
this would be correct

fickle moat
#

Hi everyone o/

So I'm working a game for a game jam, and I'm trying to make a subway surfer like game.

I'm trying to instantiate chunks, and sometimes (every checkpointChunkInterval chunks), I want to spawn a checkpointChunkPrefab that has an additional Checkpoint script attached to it.

I want to send down to the instantiated checkpoint a reference to some gameManager object.
I also want to refactor my code and extract the ChooseChunkToSpawn logic to some other method, but with my implementation, I lose the information about the type of the instantiated chunk. Is it a checkpoint? Who knows?!

Is there an elegant way to achieve my goal?
Should I change the way I do dependency injections ?

Also, I want to learn game dev. I know it's just a game jam and I shouldn't aim for an absolutely perfect code (it never is) but still

sage abyss
#

Hey, do anyone know how to set Collider's excludeLayers via script?

radiant cipher
#

Hey im having a problem when i rightclick and try adding create c# script the create c# is missing

slender nymph
#

read the available options and use deductive reasoning to find the correct one

radiant cipher
#

im unsure its my first time using unity for uni

#

Would Mono Script be the same thing?

swift elbow
#

Yes

swift crag
#

It got renamed in Unity 6, yeah

#

There are a few other options in the "Scripting" category now

lofty sequoia
#

how do I set bloom via code

rich adder
#

sometimes its easier to just add another volume with the effects you want and just play with the volume weight to fade it in or out

lofty sequoia
#

I just wanna set the intensity

rich adder
#

first one example

  if(volume.profile.TryGet(out Bloom bloom)){
      bloom.intensity.value = 0.2f;
  }```
lofty sequoia
#

yep, went with Bloom tmp;
if (_globalVolume.profile.TryGet<Bloom>(out tmp))
{
_bloomComponent = tmp;
}

dapper mirage
#

How do I change the shape and collider of a gameobject programatically? I want to allow the player to be able to crouch and turn the capsule into a circle

rich adder
#

might need to shift the center too

dapper mirage
#

I wasnt a fan of how it makes the round parts look :(

rich adder
#

you're resizing the entire thing not just the collider

polar acorn
#

How it looks and what it's colliders are need not be the same thing

dapper mirage
#

Yeah but I want it to get smaller when you crouch

#

I might not understand

rich adder
#

scale it separately though. ideally not have the graphics / collider on the same object

#

maybe animate it /fade it to a circle sprite or something

dapper mirage
#

So I should make the sprite on a separate, child object of the character?

rich adder
dapper mirage
#

Hmm good to know 👍 thank you

tiny hearth
#

I'm really strugging, losing hairs from this.

JSMessage: {"MessageType":"joinInfo","Content":"{\"CharacterId\":\"62f991a3-64b6-4970-a248-a51da054a44b\",\"UserId\":\"1a45f5f3-15fe-455b-b162-b892056e7eb1\",\"AuthenticationToken\":\"5007fefa-a923-4a2b-9570-399e08ced3ee\",\"RoomInfo\":\"{\\n\\t\\\"image\\\": 0,\\n\\t\\\"id\\\": 2,\\n\\t\\\"scene\\\": \\\"default\\\",\\n\\t\\\"room\\\": \\\"Room\\\",\\n\\t\\\"name\\\": \\\"default\\\",\\n\\t\\\"public\\\": false,\\n\\t\\\"connect info\\\": {\\n\\t\\t\\\"tcp\\\": {\\n\\t\\t\\t\\\"host\\\": \\\"localhost\\\",\\n\\t\\t\\t\\\"port\\\": 8006\\n\\t\\t},\\n\\t\\t\\\"rudp\\\": {\\n\\t\\t\\t\\\"host\\\": \\\"localhost\\\",\\n\\t\\t\\t\\\"port\\\": 8006\\n\\t\\t}\\n\\t},\\n\\t\\\"public data\\\": null,\\n\\t\\\"tags\\\": [\\n\\t\\t\\\"default\\\"\\n\\t]\\n}\"}"}

WebGL.framework.js:2429 JsonSerializationException: Unable to find a constructor to use for type ClientCommon.Models.JSEventMessage. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'MessageType', line 1, position 15.
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract objectContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, Newtonsoft.Json.Serialization.JsonProperty containerProperty, System.String id, System.Boolean& createdFromNonDefaultCreator) [0x00000] in <00000000000000000000000000000000>:0 

This is an error I get from perfectly working json in the editor/windows builds.
When compiling for WebGL, it is giving me some problems.

#

my object is very simple.

public class JSEventMessage
{
    public string MessageType;
    public string Content;

    public void SetContent<T>(T content)
    {
        if (content == null)
            return;

        Content = JsonConvert.SerializeObject(content);
    }

    public T GetContent<T>()
    {
        return JsonConvert.DeserializeObject<T>(Content);
    }

    // Serialize the EventMessage using JSON
    public string Serialize()
    {
        return JsonConvert.SerializeObject(this);
    }

    // Deserialize a JSON string back into an EventMessage
    public static JSEventMessage Deserialize(string json)
    {
        return JsonConvert.DeserializeObject<JSEventMessage>(json);
    }
}```
#

Does anyone else have experience with a similar issue, or know of a work around?

wintry quarry
#
Unable to find a constructor to use for type ClientCommon.Models.JSEventMessage. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute```
tiny hearth
#

Thank you @wintry quarry
I added a default constructor, and recieved the same message.

wintry quarry
tiny hearth
#

This is a revision after many attempts to solve it over the better part of 8 hours.

#

interesting

rancid tinsel
#

!code

eternal falconBOT
radiant cipher
#

can anyone explain whats wrong im new to coding and im following a video

rancid tinsel
covert obsidian
#

Hey, I have a current scene variable:

string currentScene = SceneManager.GetActiveScene().name;

But I added the Options scene additively, so it still detects the active scene as Game. How do I either
1. Change the active scene to Options temporarily
2. Make it check if Options exists instead of just the current scene
or 3. Remove Game scene but be able to return to it without losing any progress or anything in the Game scene


-# ❌ Old Solution: #💻┃code-beginner message and below
-# ✅ Working Solution: #💻┃code-beginner message

wintry quarry
radiant cipher
#

thank you ill give that a go 🙂

wintry quarry
rancid tinsel
#

i think there is a tab there on the second link

#

for the ballscript

wintry quarry
#

oh didn't know this site had tabs,w eird

rancid tinsel
#

this blazebin thing is so confusing lol

wintry quarry
#

the only thing on this line that could be null and cause that error is AbilityManager.Instance

#

which means AbilityManager.Instance is null

#

that means you don't have one in the scene

#

Oh one other problem is you're trying to access it from Awake in BallScript

#

Unity doesn't guarantee any execution order

#

so BallScript is probably running before AbilityManager.Instance has gotten a chance to get assigned

rancid tinsel
#

wait but thats so weird because it works for the first ball

wintry quarry
#

As a rule of thumb if you plan to access other scripts, you should be using Start not Awake

rancid tinsel
#

so is it a case of, it slows down enough doing the stuff for ball 1 that it misses the timing for the other 3 balls?

mighty compass
#

Guys I need help, I'm trying to begin creating a weapon system. So far Ive created a model in blender with working animations, my camera sits just infront of the models eyes, perspective looks great. I now need to figure out how to lineup the weapons sight with the camera's center, and make the model somehow adjust to the gun position, as well as make the gun model fire a bullet in a path towards the center of the camera when hipfiring. Any tips?

wintry quarry
tiny hearth
#

@wintry quarryThank you, that was my problem.

wintry quarry
#

just an order of operations thing

tiny hearth
#

I created a preserve attribute and added it to my classes, it's working fine.

wintry quarry
rancid tinsel
covert obsidian
wintry quarry
covert obsidian
wintry quarry
#

it seems undocumented

teal viper
mighty compass
mighty compass
#

kk

wintry quarry
mighty compass
#

thankyou

covert obsidian
#

Might just go with the second thing mentioned anyways as it seems more efficient

swift crag
#

yes, that's too fast

#

LoadScene doesn't do anything until the end of the frame

wintry quarry
#

it will not be ready on the next line of code

covert obsidian
#

How would I wait for it to load it?

wintry quarry
#

coroutine
update

covert obsidian
#

Or maybe just set it to active in the start of an options script

wintry quarry
#

anything you need to do to wait one frame

covert obsidian
#

il;l do that

covert obsidian
mighty compass
#

If I write a script that makes my characters hands attach to a gun model while it's in animation, will that stop the animation?

covert obsidian
mighty compass
#

thankyou, im going to try it out

radiant cipher
#

does anyone know why my jump mechanic isnt working?

covert obsidian
# covert obsidian Hey, I have a current scene variable: ```C# string currentScene = SceneManager.G...

Problem with old solution:
When the active scene is switched to Options, the Game scene resets along with everything in it. Solution to that problem:

Switch to instead of switching the active scene, just checking for Options existing instead. This can be done by using ```C#
bool optionsSceneExists = SceneManager.GetSceneByName("Options").IsValid();

as **PraetorBlue** suggested: [#💻┃code-beginner message](/guild/489222168727519232/channel/497874004401586176/)

**__NOTE:__ ** **Must be in a Method, doesn't work in the initializer MonoBehaviour or whatever.**
acoustic belfry
#

hi, how i can make that a proyectile detects when it touches a group of gameobjects?

#

i have the script for what happens when that happens, but not how i can make it happen

#

originally i made up the script for work for a single enemy, using it code, but i didnt fully like it, this is the script

using UnityEngine;

public class rifle_bullet_script : MonoBehaviour
{
    public int riflebulletdamage = 5;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    private void OnTriggerEnter2D(Collider2D collision)
    {
        tuetue_script enemy = collision.GetComponent<tuetue_script>();
        if (enemy);
        {
            enemy.TakeDamage(riflebulletdamage);
            Destroy(gameObject);
        }
    }
}
wintry quarry
#

In your code right now it's destroying itself as soon as it touches any object, so it's really only going to be able to touch as many objects as it can manage to touch in a single frame before it gets destroyed

wintry quarry
covert obsidian
acoustic belfry
#

this is the enemy script

#
    {
        currenthealth -= Damage;
        StartCoroutine(FlashWhite());
        if (currenthealth <= 0)
        {
            Die();
        }
    }

     void Die()
    {
        Destroy(gameObject);
    }

    private IEnumerator FlashWhite()
    {
        spriteRenderer.color = Color.white;
        yield return new WaitForSeconds(0.2f);
        spriteRenderer.color = ogColor;
    }

}
    ```
wintry quarry
#

It will work for multiples

acoustic belfry
#

in theory everything works as desire, the issue here is, it only works for this enemy

wintry quarry
#

except that it immediately destroys itself

acoustic belfry
#

the game will have a huge amount of different clases

#

i want this to work for a group of gameobjects, instead of just this fella

wintry quarry
#

I thought you were saying "How do I make this hit multiple enemies at once"

acoustic belfry
#

ah, no

#

its the first thing

#

how i can make this work for any type of enemy

wintry quarry
#

The best answer is to change this:

        tuetue_script enemy = collision.GetComponent<tuetue_script>();
        if (enemy);
        {
            enemy.TakeDamage(riflebulletdamage);
            Destroy(gameObject);
        }```
to this:
```cs
        EnemyHealth enemy = collision.GetComponent<EnemyHealth>();
        if (enemy)
        {
            enemy.TakeDamage(riflebulletdamage);
            Destroy(gameObject);
        }```
#

and just put EnemyHealth on all your different enemies

#

there's no reason you need to rewrite "having health and taking damage" for every different type of enemy

#

they will all do that the same way

#

hence just make a dedicated script for it and reuse it everywhere

#

Also note I removed the ; you put in your code before after the if statement. That was a bug and will cause errors @acoustic belfry

acoustic belfry
#

oh wow

#

well thanks a lot

#

:3 thx

maiden relic
#

how do I stop an animation from effecting the models position

maiden relic
acoustic belfry
wintry quarry
#

And have the animator only animate the child

#

Not the root

maiden relic
#

alright thanks

wintry quarry
acoustic belfry
#

but i mean, in what part of the script?

wintry quarry
#

In what part of what script

#

It would be its own script

acoustic belfry
wintry quarry
#

Neither

#

It's its own script

acoustic belfry
#

o h

wintry quarry
#

As I said

acoustic belfry
#

ah, ok, and what i put on it script?

wintry quarry
#

I don't understand the question

acoustic belfry
#

im sorry i got lost

acoustic belfry
wintry quarry
#

You don't replace anything

#

The enemies would have both scripts on them

#

Remove all the health and damage logic from the original enemy script

#

Move it to the new script

#

And reuse that new script on all your enemies

acoustic belfry
#

aaaaaaaaaaaaaa, now makes sense

#

now i get it

#

thank you :3

acoustic belfry
#

i tested my script and the enemy health lows, it works, but it doesnt "shine", i mean, the sprite doesnt become fully white when its hit, what i did wrong? I set up the spriterendered to the sprite object, it should work

using System.Collections;


public class enemy_hurt_script : MonoBehaviour
{

    public int maxhealth;
    public int currenthealth;
    public SpriteRenderer spriteRenderer;
    private Color ogColor;

    void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        currenthealth = maxhealth;
        ogColor = spriteRenderer.color;
    }

    // Update is called once per frame
    public void TakeDamage(int Damage)
    {
        currenthealth -= Damage;
        StartCoroutine(FlashWhite());
        if (currenthealth <= 0)
        {
            Die();
        }
    }

    void Die()
    {
        Destroy(gameObject);
    }

    private IEnumerator FlashWhite()
    {
        spriteRenderer.color = Color.white;
        yield return new WaitForSeconds(0.2f);
        spriteRenderer.color = ogColor;
    }
}
rich adder
eternal falconBOT
rich adder
#

btw sprite renderer.color is just a tint for the original sprite, its not going to make the sprite full white

kindred mulch
#

quick question

#

can someone explain lightmapping to me?

timber tide
#

that's not really a question

rich adder
#

something can be easily googled

kindred mulch
#

Im not understandin it though

acoustic belfry
rich adder
kindred mulch
#

oh

#

right

rich adder
#

its difficult to read especially on mobile through discord

acoustic belfry
#

aaah, those links

#

i get it

#

sorry

rich adder
unreal snow
#

How to init script in the first Scene? Should i place script in mainMenu?

(CursorManager script with 1 instance for all scenes)

acoustic belfry
woeful bridge
#

Ok i'm a complete beginner coming from roblox
I'm having a issue where the character controller .IsGrounded just always returns false no matter what

    void Update()
    {   
         characterController.SimpleMove(Vector3.down * gravityValue * Time.deltaTime);


        Debug.Log(characterController.isGrounded);


        if (Input.GetKeyDown(KeyCode.Space) && characterController.isGrounded)
        {   
            characterController.Move(new Vector3(0, jumpHeight, 0));
        }
        
    }```
#

And yes i'm on the ground lol

#

I checked the docs for isGrounded and it was the least helpful doc that has ever documented so I had to ask here

rich adder
woeful bridge
#

Oh so should I just raycast?

rich adder
#

Normally you make your own

woeful bridge
#

every tutorial ever I saw just used isgrounded

rich adder
#

yeah raycast is good but too thin imo

#

I use an overlap or spherecast, depending if i need the hitinfo

woeful bridge
#

whats the solution then? I'm not really sure what unity has yet tho I assume if roblox has it unity probably does too

#

oh that makes sense

#

So I should just use a rigidbody and not a character controller?

rich adder
#

isGrounded works on when the CC was last move, but idk barely ever used SImpleMove

woeful bridge
#

or is it just the isgrounded thats trash

teal viper
#

I'd just recommend not using CharacterController

woeful bridge
#

cool

#

depressing but cool

rich adder
#

CharacterController is okay but with Move you have to make your own gravity and other forces

woeful bridge
#

yeah but I also don't have to code a lot of other stuff to be fair lol

#

but yeah I can do that

rocky canyon
#

true.. but after a min u learn other cool programming things..

woeful bridge
#

I'll research the other stuff thanks

rich adder
#

Riidbody is good too but annoying sometimes to fully control it

woeful bridge
#

I know how to do the rigid body stuff I just saw everyone used that tutorial wise

#

I've been coding for 3 years now in roblox which I'm so sick of roblox so i'm trying out unity lol

rocky canyon
#

gravity, knockback, magnitudes.. normalizing.. lerping etc etc

rich adder
#

Kinematic helps getting more precise rigidbody movement but it doesn't give you collisions if you knock into walls/obs

#

requires you to use something like rb.SweepTest

woeful bridge
#

I have this so far for my rigidbody code

using System;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.TextCore.Text;


public class PlayerMovment : MonoBehaviour
{
    public float speed = 50.5f;
    public float jumpHeight = 10f;
    public Rigidbody rigidBody;

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

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        rigidBody.linearVelocity = new Vector3(horizontal * speed, rigidBody.linearVelocity.y, vertical * speed);
        
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded) {
            rigidBody.linearVelocity = new Vector3(rigidBody.linearVelocity.x, jumpHeight, rigidBody.linearVelocity.z);
        }
    }

        void OnCollisionStay(Collision collision)
    {
        ContactPoint point = collision.GetContact(0);

        Debug.Log(point.normal.y);
        if (point.normal.y >= .8) {
            isGrounded = true;
        } else {
             isGrounded = false;
        }
    }

            void OnCollisionExit(Collision collision)
    {
        isGrounded = false;
    }
}
#

But I'm not done

#

I'm just messing around i'm very brain rotted by roblox

rocky canyon
rich adder
#

I would still not rely on OnCollisionStay for grounding

woeful bridge
#

yeah it was just the only idea I had i legit just started unity today

#

I started 3 hours ago lol

rich adder
#

too many possiblities to mess up or mis-detect

#

you good lol

#

if you want a quick "dirty" solution use the KCC or the unity Starter Assets controllers

woeful bridge
#

I tried godot but going from roblox to godot broke me so I decided unity lol

rocky canyon
#

lol.. i feel like unity gonna give equal results

woeful bridge
#

UI is a lot more similar to roblox

#

so idk

rocky canyon
#

perhaps..

rich adder
#

unity has soo many things that godot still catching up to

woeful bridge
#

plus godot is a lot more simplified and lightweight so I gotta learn how to do a lot more there and I want my hand held just a little lmao

rocky canyon
#

godot ui isnt that bad.. i personally enjoy it

rich adder
#

Godot c# is just not polished enough for me and missing so many things

woeful bridge
#

plus godot 4 is so new not as many docs and tutorials

rocky canyon
#

ya, there ya go ^

rich adder
#

pythony like syntax grosses me lol

rocky canyon
#

same same..

woeful bridge
#

I mean I coded lua so nothing is that bad to me LMAO

rocky canyon
#

discord bot building flashbacks.. terrifying

woeful bridge
#

I love me some lua

rich adder
#

c# is fairly easy and nice

woeful bridge
#

I just gotta get use to types

#

don't gotta do that in lua

rich adder
#

last time i used LUA was making mods for Gmod

rocky canyon
#

hmm.. navmeshsurface seems to be tucked in here now

rich adder
#

fun times

woeful bridge
#

yea most mods are made in lua

#

do be sorta the point of lua

rocky canyon
#

i thought it was under using UnityEngine.AI;

rich adder
rocky canyon
#

ya, i just never remember needing to add an extra package for it

#

so thats 🆕 to me

rich adder
#

Oh that was when it came from Github

rocky canyon
#

ya, i refused to use the github link

rich adder
#

1.0 was released around 2022 came out i think

untold shore
#

Hey yall. Having some trouble, as every time I attempt to destroy the children in my object, it still says I have all children there while I don’t. I don’t know if it’s my code or anything, but it’s breaking some parts of my game. Sorry for the horrible quality, I’m on a roadtrip and I can’t get WiFi on my computer to text it here

rocky canyon
#

never done that yet... lol i feel better installing via the registry

rich adder
#

thats when old baking modes were discarded

woeful bridge
#

So for overlap I assume I just make a non collidable part of my character and check if something collides?

eternal falconBOT
rich adder
#

use if you go for overlap or cast use the non-alloc version

rocky canyon
#

oh i jsut finished the sentence

untold shore
#

😂 yall are okay. Gonna take me a minute to copy, it’s def difficult to retype code with a phone.

rocky canyon
#

nah.. if its an android it simple..

woeful bridge
#

I assume character controllers are newer to unity? or are they just buggy since forever

rocky canyon
#

click hold.. drag

rich adder
#

i usually make a hotspot with my phone

rocky canyon
#

thats the only way..

rich adder
woeful bridge
#

oh why are they so buggy then? Not in the priority list of fixing?

woeful bridge
#

Idk grounded seems to be fucked and other people I asked just said it had a lot of bugs and wasn't worth it

rocky canyon
#

my CC is smooth as butter

woeful bridge
#

but they were also like ex unity devs so

rich adder
woeful bridge
#

oh kk

#

idk what simplemove even is lol

rich adder
#

SimpleMove vs Move

woeful bridge
#

yeah ik meant the difference

rich adder
#

oh look at the docs

woeful bridge
#

kk

rich adder
#

SimpleMove tries to apply gravity* speed n whatnot

woeful bridge
#

So in your personal opinion should I just a rigid body or the character controller

#

And i'll go from there