#💻┃code-beginner

1 messages · Page 79 of 1

verbal dome
#

Yeah that's what I meant with the FixedUpdate thing.

summer stump
#

The Input should be in Update, only movement in FixedUpdate

#

Oh, wait. It's in both?

verbal dome
#

Getting continuous input is totally fine in FixedUpdate

flint wind
verbal dome
#

That's a common misconception

flint wind
verbal dome
#

Because one-time inputs like GetKeyDown will work poorly in FixedUpdate

summer stump
summer stump
verbal dome
#

And according to my testing, I actually recommend getting the input in FixedUpdate.
FixedUpdate runs just before Update. So if you use the input values from Update, your FixedUpdate will use the last frame's input

#

Does that make sense?

#

It causes a 1-frame delay which is not easy to spot but worse regardless

summer stump
verbal dome
#

Yep, continuous only.
Surprisingly I have never heard anyone else mention it, kinda figured it out on my own🤔

#

I'm such a pioneer

flint wind
#
    {
        rb = gameObject.GetComponent<Rigidbody>();
        animator = GetComponent<Animator>();
        sr = GetComponent<SpriteRenderer>();
    }

    // Update is called once per frame
    void Update() 
    {
        RaycastHit hit;
        Vector3 castPos = transform.position;
        castPos.y += 1;
        if (Physics.Raycast(castPos, -transform.up, out hit, Mathf.Infinity, terrainLayer))
        {
            if (hit.collider != null)
            {
                Vector3 movePos = transform.position;
                movePos.y = hit.point.y + groundDist;
                transform.position = movePos;
            }
        }
    }

    
    private void FixedUpdate() 
    {


        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");
        Vector3 moveDir = new Vector3(x, 0, y);
        rb.velocity = moveDir * speed;

        rb.MovePosition(rb.position + moveDir.normalized * speed * Time.fixedDeltaTime); 

        animator.SetFloat("Horizontal", x);
        animator.SetFloat("Vertical", y);
        animator.SetFloat("Speed", moveDir.sqrMagnitude);

        
        if(x < 0)
        {
            sr.flipX = false;
        }
        else if (x > 0)
        {
            sr.flipX = true;
        }
    }

}
verbal dome
#

Why did you change it?

#

I said "yes, that's what I mean" when you showed your updated code

#

Keep rendering related things in Update: animator, spriterenderer

flint wind
#

Sorry let me change that

#

This is my first time using unity so sorry if im being annoying lol

#
        animator.SetFloat("Horizontal", x);
        animator.SetFloat("Vertical", y);
        animator.SetFloat("Speed", moveDir.sqrMagnitude);
#

added that as well

verbal dome
#

To Update, right?

flint wind
verbal dome
#

Now remove the rb.velocity line from Update
Also using both velocity and MovePosition is weird, maybe try with velocity only?

#

And you might want to add .normalized after moveDir in the rb.velocity line, maybe not

verbal dome
#

Remove the rb.MovePosition line. You are already moving the rb with velocity

verbal dome
#

Also, replace transform.position = movePos with rb.MovePosition(movePos). If your object has a rigidbody, you shouldn't move it with transform. Use rigidbody methods instead

verbal dome
#

Looks better, try it out

#

You probably need to make speed higher now that you removed the MovePosition line

cunning heath
#

How can I manually stop an editor script (Sometimes it runs for 5-10 minutes or so and I need to stop it)

#

Any keyboard shortcut?

verbal dome
# flint wind

It really looks like another script is changing the flipX too. It shouldn't behave like this

#

Or maybe an animation is changing it

teal viper
#

Is it async? A coroutine? Or just an update that runs in the editor?

cunning heath
#

just regular for loop and recursion

teal viper
#

Well, that would just freeze the editor while it's executing. And you can't stop it from the outside.

cunning heath
#

Ah so I have to force quit then

teal viper
#

You could try manipulating the loop from the debugger if you need to stop it right now.

#

But better add a stopping logic/make it execute asynchronously after that.

verbal dome
#

I do suggest async or coroutines for things like map generation. For coroutines in the editor you need the EditorCoroutines package.
It gives you a chance to visualize the generation process too

#

Watching your map get formed is fun and helps with debugging

cunning heath
cunning heath
flint wind
verbal dome
flint wind
teal viper
#

The debugger is a feature of an ide(visual studio in your case). You could modify the value that the loop condition checks to break out of it early.
If you don't know how to use the debugger, it's a whole separate topic.@cunning heath

verbal dome
teal viper
cunning heath
#

ah

#

So you mean to write this as an editor coroutine and have a method to stop execution if i need to as well

flint wind
verbal dome
#

And tell me if it changes anything

verbal dome
# flint wind

Hmm... Okay next test, comment those lines out completely. Surround that same code with comments: cs /* code here */

#

It's like deleting the code, but you can bring it back by removing the /* */

frozen surge
#

Hi what usually causes when your using an asset that is working on the sample but when you used it to your own character it doesnt interact with it?

verbal dome
#

Do this:

  1. Use your code editor to search the scripts for flipX
  2. Check the animations that you are using and see if they are modifying SpriteRenderer.flipX
frozen surge
teal viper
teal viper
verbal dome
#

Another important one @flint wind:
3. Check if anything is modifying your player's transform.localScale

#

Including the animations

rich adder
frozen surge
frozen surge
rich adder
frozen surge
rich adder
#

then disable the main solid collider when you enter trigger

teal viper
teal viper
#

That doesn't make it much clearer.

verbal dome
#

Falling platform or a platform that you can fall through?
Falling platinum?

frozen surge
verbal dome
#

What should happen when the platform hits you?

#

And is it really a platform, or just solid?

frozen surge
verbal dome
#

Ah now I see. I was also thinking something different

#

You should just say that in the first place

teal viper
# frozen surge making like a wipe out game for assignment

Still not entirely clear. Never heard of that game. Maybe explain the general idea of the game and/or share a link to the game you're referring to. Google provides several different results and I'm not sure which one you're talking about.

verbal dome
#

Like a block that falls when you step on it, right?

rich adder
#

I think they mean a game like obstacle course like fall guys or w/e

flint wind
verbal dome
#

Just do all the 3 steps that I listed. Something is clearly modifying either your flipX or transform.localScale

#

But yeah, usually sprites face right, so you might wanna fix that

flint wind
verbal dome
#

3 steps

#

That's just one step, or two, depending on what you mean with "x" of the sprite

inner skiff
#

Would someone here be able to help me with my parallax script or settings in unity? I’m running into this wild problem where I need to make my images like 100x bigger as they get further into the background, making it near impossible to design a level

wintry quarry
inner skiff
#

Oh yeah, I think it is set to perspective. Should I be using Orthographic instead? I tried switching to that but once I do I lose my parallax effect entirely

wintry quarry
#

For a 2D game generally you use Orthographic - yes

#

In 3D parallax would come automatically, as it's a side effect of perspective effects

#

2D games often use scripts to simulate parallax by moving images around at different rates depending on the "distance" of the image to the camera.

#

When you said "my parallax script" I assumed you were using or creating such a script

inner skiff
#

Yeah I have a basic script made for parallax scrolling but it doesn’t seem to work when I set the camera to Orthographic

wintry quarry
inner skiff
#

Ahh okay. Tyty. Just having a lead on where the problem exists is nice. I’ll start poking around in there

inner skiff
eternal falconBOT
inner skiff
#

how do i link it once i'm done?

#

Do I just copy and paste the whole code now?

wintry quarry
#

no you share the link from the paste site

#

i don't know which one you're using but generally you press a save button somewhere then share the link here

inner skiff
#

Noice, I think that’s it

wraith wadi
#

hey Thank you soo much
i finally understand it now and I did it.
The aim is perfect now.
i am still new and learning vectors and unity. Thank you 😍

gloomy urchin
flint wind
#

i also have another issue

#

its with my billboard script

wintry quarry
verbal dome
flint wind
teal elk
#

I’m currently working on a project in Unity and I’ve encountered an issue that I’m having trouble resolving.

The problem lies in the instantiation of a gun object in my game. Here is the line of code where the issue occurs:

equippedGun = Instantiate(gunToEquip, weaponHold.position, weaponHold.rotation) as Gun;
equippedGun.transform.parent = weaponHold;```
The gunToEquip is supposed to instantiate at the weaponHold.position with the weaponHold.rotation. However, it seems that the gun is being instantiated with incorrect values. I’ve checked the gunToEquip prefab and the weaponHold’s transform values, and they seem to be set correctly. The equippedGun is also correctly set as a child of the weaponHold.

Despite this, the gun does not appear as expected in the game. I’m unsure if the issue lies within these lines of code or if it’s related to another part of the script or the game setup.                                                                                  
I would greatly appreciate any guidance or advice you could provide on this issue. Thank you for your time and assistance.                                                                                                                                                                                                                                                                                                                                                                                                                                                      I’ve attached an image of the gun as a prefab. This image shows the gun when it’s manually dragged to the weaponHold point in the scene. There’s also an image of the gun when it’s instantiated at the weaponHold point during runtime.
raven trout
#

What does the WeaponHold rotation look like?

#

On the gun, when its attached to the WeaponHold in the editor can you set all of the rotation values to zero and see if it looks like the second picture

teal elk
raven trout
#

Yeah so thats the problem

#

you could make another gameobject with the correct orientation, as a child of the current WeaponHold

#

and then use that as the weaponhold

#

and it should work

teal elk
twin hill
#

Hi guys im new i have a question, Why does the line extend from a fixed point? I can't take it where I want. i need it like second img protected virtual void OnDrawGizmos(){ Gizmos.DrawLine(transform.position, new Vector3(groundCheck.position.x, groundCheck.position.y - groundCheckDistance)); } }

#

okkey i fix

#

it

distant mesa
#

anyone know how to fix this?
tried reimporting, restarting, deleting library, changing the manifest.json file etc. This also happends when we try to make a new Unity project and add OpenXR in.

queen adder
#

Can anyone help me with making a limited radius vision in a 2d side scroller? I couldn't find anything on it and i just want it to do this to make a point for a project for school.

rare basin
#

what have you done so far

queen adder
# rare basin what exactly do you need help with

i've made all the movement for the sprite and I am currently working on the enemies. What I aim to do is make it so that the player can not see the full screen and only a small circle around them that follows them sort of like this

#

I'm doing this because I want to make a top down game and I have to talk about the disadvantages of what I want to achieve in a side scroller

rare basin
#

best would be to write a custom shader for that

#

or you can try with just a simple light attached to your character

#

but shader would be the best

#

or, you can also achieve it with layers and masks

queen adder
#

okay thank you, do you have any examples or videos to recommend for this?

rare basin
#

make a layer mask, set the camera culling mask, add this layer there

#

add Mask component to Camera

#

then make a script for it

#

with X radius

#

so the camera will render only things inside this radius

#

and set camera's solid color to black

queen adder
#

thank you

young smelt
#

For some reason when I change scenes, the event in the new scene bugs out and gives error

#

god I can't even explain the error because I don't even understand it

#

forget it

rare nexus
#

Hi everyone! I'm having an issue where when I make a prefab, the transforms I set in my script don't save and change to "None" (blank).

#

A photo for context.

fossil drum
rare nexus
#

I'm refrencing the transforms of something literally in scene though?

#

Like the transforms I'm mentioning to the script are children of the player, which is active. Maybe I'm misunderstanding what you mean.

fossil drum
#

Prefabs don't know anything about the scene, that's my point. You can also drop that prefab into a scene without a Player for example.
The weapon stuff it knows, because its inside the same prefab.

#

The Player, Gun Container, and FPS cam are not part of this prefab right? Those are things inside the scene.

rare nexus
#

No

#

So if I'm understanding right. The transforms have to be PART of the gun this script is on for this to not happen, and the fact that I'm referencing my player is why this happens?

fossil drum
#

Yeah, it can't reference things not in the prefab. So normally (as far as I know, I normally don't use MonoBehaviours anymore) you get the references from either a Manager object that has those objects cached or you search for it.

rare nexus
#

You know, now that you're mentioning it, this makes sense.

#

How's Unity supposed to reference the transform of a totally different object every time when this weapon prefab spawns in?

ancient zenith
rare nexus
#

I didn't think about it like that. And I'm not using a manager yet, so. This answers my question.

ancient zenith
#

most the time, people want something and they don't realize what they want isn't what they need

modest dust
#

A prefab is a "template" of a GameObject which you can instantiate in any given scene.
You cannot reference anything scene-related in the prefab which is not a part of that prefab. Think of it as if the prefab was in a separate scene than your player, etc.

#

If you want references then pass them into it when instantiating

rare nexus
#

Yeah, I realize that now

#

I didn't before

modest dust
#

Some kind of Init method

rare nexus
#

Apparently, things are more specific and require more thought than I had expected. Which is fine. We live and learn.

fossil drum
craggy lava
#

How do i make a firework rocket like in Firework mainia??

fossil drum
ancient zenith
fossil drum
#

Oh you removed it in the other channel, nevermind then.

teal viper
rare nexus
#

My grab script is what allows me to pick up (and by extension, drop) weapons.

craggy lava
#

So i want to make a firework you light with a lighter tool but i need a firework rocket that can be launced and then if it hits something it would do like in the real world like bounce and when it explodes it would like have a explosion force and this thing might be in code general but i will try beginner first

rare basin
#

what have you done so far

fossil drum
# rare nexus On the topic of a Manager. How would I do it? Just a scriptable object to store ...

I'm not saying this is the most optimal solution, but I had a singleton Manager inside the scene which I can just reference everywhere, which already knows the most common references to objects.
So then you can do this in the Awake methods of your scripts that need the reference:
player = Scene1Manager.Player; or what ever you want. That way you don't have to Find all the things again, which could provide some hickups in the FPS if you do a lot of those at once.

rare basin
#

share some code

rare basin
#

correct me if im wrong, these functions no need to exist, atleast for me

craggy lava
# rare basin what have you done so far

I have a Particle Graph that launches a firework in the air but like it cant like shoot sideways and bouce of like a slope and there is no force when it explodes

rare nexus
#

I also have no idea how to use scriptable objects still, despite having been told by someone that they're "Super powerful". But to be fair I am a beginner, so. Need time to wrap my head around them.

rare basin
#

you are asking such general questions

fossil drum
#

They are nice convenience methods that shouldn't be in a production ready game. I agree with that. Just testing out stuff without the need to serialize anything could be nice in some cases.

rare basin
#

it didin't even run

fossil drum
#

Yeah, that's sounds terrible.

rare basin
#

it was funny tho xD

craggy lava
rare basin
craggy lava
rare basin
#

show the code you've done so far

craggy lava
#

its a VFX graph

rare basin
#

this is a code related channel

craggy lava
#

true

rare basin
#

if you want to add force to your particles from VFX graph i believe there is "Add Force" method in there

#

Add Block > Forces > Add Force

#

but you might need to make your own script for more advanced physics you want to achieve

craggy lava
ancient zenith
#

they are good for storing data that will not change during runtime in game. They help keep the game file size a lot smaller when you build the game.

rare nexus
#

Yes, I know what they're for and I've watched tutorials. I don't know how to use them because code related stuff is a hard to remember for me.

ancient zenith
#

Well you just need a refrence to the scriptable object then take the data from the scriptiable object. That is all.

timber tide
#

They're just data objects at core, otherwise you'd use stuff like plain text or json if you wanted to say give your gun a default amount of stats like damage and bullet capacity.

#

what makes them much more useful is we can reference other project assets or other data objects directly from the inspector without having to explicitly code in their path.

ancient zenith
#

so in my game i literally have 1 enemy prefab for all my enemies in my game. At runtime I make a enemy pool of 1,000 enemies. Then I just move them around and give them a new refrence to an enemy scriptable object. (some games you don't want to do this but for this game its fine and good)
that code there in the method "ChangeSprites()" I have a refrence to the scriptable object which actually contains all the data of this enemy so I can change this 1 enemy prefab to the enemy I want.

rare nexus
#

I love how the two of you help me understand this more than 97% of the tutorials I've watched and in less time 😆

ancient zenith
#

Majority of tutorials don't teach you the correct way of doing things.

#

The reason I make a pool of enemies is cuz this game there are thousands of enemies being killed in a minute

#

So instead of Instantiating/Destroying them, I just disable the enemy, then move and activate it again when needed

rare nexus
#

Because instantiating would cause performance issues right?

ancient zenith
#

Whenever you destroy something, it creates garbage and the comp has to get rid of it sometime which then can cause lag spikes

#

So I keep my 1000 enemies in the game at all times so there is no garbage

#

They are all made by 1 enemy prefab. But I take enemy scriptable objects to replace their sprites at runtime.

rare basin
#

instead of having one big SO with all the weapon data, you can split it into multiple SO

#

so you have WeaponData (SO) with references to WeaponAudioData (SO), WeaponVFXData(SO) etc

#

easier to work with in bigger projects

ancient zenith
#

i only have attack and hit audio though, and it's only attack and hit vfx

#

but i can see that

rare basin
#

yea, if you grow this project

#

it becomes kinda pain to manipulate this big chunk of SO

#

instead if you want to change the hit VFX of a certain weapon, you just go into PistolVFXData for example

#

and change it there

#

it also gives you more control, so if you want to have List<VFX> for each weapon and pick one randomly everytime you shoot

ancient zenith
#

i don't have issues currently

rare basin
#

you can just make GetRandomHitVFX() inside the PistolVFXData.cs

#

combining this with Odin's Inspector [InlineEditor] attribute you can do things very fast and efficient

ancient zenith
rare basin
#

well, it's always good to make a good, clean code, no? ;p

#

doesn't matter if its big or small project

#

maybe in the future you will come back to this project and want to extend it with some mechanics

#

it's also keeping the SOLID principles

ancient zenith
#

so you think I should have more S.O. for 1 weapon even if I'm just using what I told you?

rare basin
#

imagine having one big Player.cs class with everything inside

#

movement, healthsystem, upgrade system, shooting system

#

instead of small (single-responsibility) classes for it

#

also, just a small thing i've noticed, maybe you are not aware

bool IsElite()
{
    return Ref.gm.enemyPoolIndex != 0 && Ref.gm.enemyPoolIndex % 100 == 0;
}
#

you can do it like that instead of splitting into return true/return false

ancient zenith
#

yea haha, so true

thin sedge
#

Hi! I'm trying to make a start for my platformer game that is supposed to have an animation when the player runs by the start arrow and not play at all when the game starts befor collision. Any ideas?

rare basin
#

What have you done so far?

#

Show the code

#

And what exactly do you have an issue with

thin sedge
#

So no code

rare basin
#

this is a code related channel

thin sedge
thin sedge
humble condor
#

how i set VideoClip on run time?

rare basin
#

what is that

#

VideoPlayer.clip = yourClip variable

hexed terrace
#

1- Why did you leave off the ; on both lines
2- What's the error? Mouse over the red lines -> read the error

humble condor
rare basin
#

configure your ide

#

read the documentation

hexed terrace
#

it is configured

rare basin
#

right

raven kindle
#

Can someone help me out? I wanna use a script to generate tiles inside my game, i have watched tutorials and still dont understand, can anyone help?

rare basin
raven kindle
#

Linking the script with the right tile on a tilemap

rare basin
#

you gave 0 context of how this should work

#

and what have you done so far and what do you need help with

timber tide
#

only time I do extend from the base is for type constraints, but otherwise I try not to tunnel the logic into different derivatives.

#

type checking / component checking is fine for most of my cases anyway

short grove
#

Hello, is there a way to make the object not jump multiple times when collided to the walls

short grove
rich adder
short grove
#

Under print jump

rich adder
eternal falconBOT
short grove
#

I cant

#

My laptop doesn't have vpn

#

So any ideas?

rich adder
#

mate if you're not willing to share the code lookup how to make grounded check better

short grove
#

Ok wait a minute

rich adder
short grove
rich adder
#

yeah this wont be a suitable way to do it , guaranteed

ancient island
# short grove

r u checking for every platform to see wich one is the player touching?

#

lol

rich adder
#

check out the video I've sent. They do this properly use physics casts @short grove

rich adder
#

that wont work for exact reason why its not working now lol

#

if you touch a platform from the sides you can still be "grounded"

short grove
#

I should use arrays?

rich adder
#

no arrays got nothing to do wtih it, you need physics queries

#

in this case I've sent a boxcast vid

short grove
#

Ok

#

Thanks

rich adder
#

think of it like an invisible box thats gets thrown in the direction you pass it , tells you anything thats hit in box

queen adder
#

Hey guys i made a scriptable object in my unity project.
Its called World. It holds my other scriptable object which is the levels.
Everything was working great last night.

But when i opened my project today i keep getting an error
"Unknown error occured while trying to load scriptable object World"

And my world scriptable object isnt that funny blue and orange block thing anymore. It just shows like a white little page / paper next to the name.

My level scriptable objects are all the same still and working.

Anyone know what i could do?
I tried google with no luck

#

Sorry if this is the wrong channel

celest ravine
#

Hey there, does anyone know a good way I could have all my Skins for my game in one place. The skins are a png that I am making a sprite with. But the problem is I have 2 scenes and the information has to be accessable in both scripts. And I would want it to be easily done in the editor. I made a class like this ```cs
[Serializable]
public class Skin
{
public int skinId;
public Texture2D skinTexture;
}

and then I am making a List of that type Skin, which is public, so that I can drag the skin pngs in there.
```cs
public List<Skin> skinList;

I am just facing the problem that I have to create this list once in each scene, which is a really bad way of handling this. And I would like to have this information in one place where it is accessible from any script in any scene. Any suggestions on how this can be achieved? And is it possible to have the skinId increase by 1 by default?

rich adder
celest ravine
timber tide
rich adder
celest ravine
celest ravine
rich adder
#

its against server rules regardless

celest ravine
rich adder
celest ravine
timber tide
#

Static class should be fine too honestly if it's just data

#

then populate it on start, many ways you can go about it

rotund abyss
#

Hi when I wanted to extract the game as an .exe file it didn't work and I looked in the settings and I must have screwed something up and now it says this in the console: Call to DeinitializeLoader without an initialized manager. Thanks for the help.

nimble apex
#

it seems that this problem is on XR settings?

rotund abyss
nimble apex
digital lynx
#

Hello, im having this error for some reason in my code Anybody know why?:
Assets\Scripts\ThirdPersonMovement.cs(26,89): error CS0103: The name 'cam' does not exist in the current context

The code:

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

public class ThirdPersonMovement : MonoBehaviour
{
CharacterController controller;
float turnSmoothTime = .1f;
float turnSmoothVelocity;

Vector2 movement;
public float moveSpeed;

void Start()
{
    controller = GetComponent<CharacterController>();    
}

void Update()
{
    movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;

    if (direction.magnitude >= 0.1f)
    {
        float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
        float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
        transform.rotation = Quaternion.Euler(0f, angle, 0f);
        
        Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
        controller.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);
    }
}

}

eternal falconBOT
rotund abyss
rich adder
rotund abyss
#

this error only shows up when I start the game and turn it off again

rich adder
nimble apex
#

@digital lynx

rich adder
#

do you get actual errors?

rotund abyss
#

only this warning

digital lynx
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ThirdPersonMovement : MonoBehaviour
{
    CharacterController controller;
    float turnSmoothTime = .1f;
    float turnSmoothVelocity;

    Vector2 movement;
    public float moveSpeed;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;

        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);
        }
    }
} 



rich adder
digital lynx
digital lynx
#

i was just following a youtube tutorial

rich adder
#

follow it again but better

#

also configure your IDE(Code Editor)

#

its not underlining error?

digital lynx
#

https://youtu.be/iHzAwGg--LM?si=MO7rY811NqQmK5f9&t=203

I highlighted this part in the video.

Get access to the project files!
https://www.patreon.com/JTAGamesInc

In this tutorial we'll go over third person movement. Hope this helps on your game development journey!

JTAGames is unfortunately closing it's doors. Jon-Tyrell (The guy who's voice you hear 90% of the time) is moving to "Keahunui Technologies" An unofficial company / brand...

▶ Play video
rich adder
eager elm
rich adder
digital lynx
#

thanks

rich adder
eternal falconBOT
rotund abyss
rich adder
#

it shouldnt prevent a build afaik

rotund abyss
#

ok thanks you one more thing where can I download JDK?

rich adder
#

Cog wheel icon on the editor Installs tab

amber spruce
#

so i know for unity with number variables you can just do the variable then ++ to increase it by 1 is there a way to do that but increase it by like 5 or 6

amber spruce
#

so this inscreases it by 5

                numberOfEnemiesInWave += 5;
rotund abyss
amber spruce
#

k thanks

rich adder
rotund abyss
#

so there?? i dont know

rich adder
#

you'd hve to manually do it. also this is not coding question and should go in #💻┃unity-talk

raven kindle
#

I am very new, how can i assign a tile to a gameobject?

gaunt ice
#

create a field of type tile, assign it in inspector

raven kindle
rich adder
#

you haven't explain

raven kindle
#

i am trying to generate a platform with a script

#

but first i need to make a game object with the tiles

#

soo when i create it, it just makes a new object

rich adder
#

thats not how tiles work

raven kindle
#

i have a gameobject atm, it has one tile in it

#

oh

rich adder
#

tiles aren't gameobjects

#

no first yu reference the tiles you want to place inside a script, then reference the tilemap so you can place said tiles

raven kindle
#

but i want to delete them after i use too

#

doesnt each platform need to be its own object?

rich adder
#

no

rich adder
#

You store the tiles positions to where they have been placed

ruby python
#

Hi all, was just wondering if anyone had a resource/tutorial for a grappling hook/gun script with an animate 'rope' BUT, where the animation/'growing' of the rope works backwards also? Literally everything I've found has the rope just disappear when you let go of the mousebutton. 😕

raven kindle
#

and can i group multiple tiles together, so when it generates, it spawns 3 at a time?

rich adder
#
public Tile SomeTile```
raven kindle
#

but how can i group mutlple tiles into one?

#

i have all the individual ones

#

i want these 3 to be joined

rich adder
raven kindle
#

oh

rich adder
#

or just use a image editor and make it 1 piece

raven kindle
#

i am watching this tutorial, and he is doing it completely different: https://www.youtube.com/watch?v=vClEQ1GqMPw&list=PLfX6C2dxVyLylMufxTi7DM9Vjlw5bff1c&index=3

Learn how to build a 2D Endless Runner in Unity - In this video, we create a spawner that will endlessly spawn new obstacles of different varieties.

Next Video: https://youtu.be/sbJPs-Lcogk
Playlist: https://www.youtube.com/playlist?list=PLfX6C2dxVyLylMufxTi7DM9Vjlw5bff1c

Source code & Assets: https://www.patreon.com/posts/85934623
Patreon: ht...

▶ Play video
#

ok

rich adder
#

major differences

#

a tilemap is a self contained gameobject

#

with its own assets

#

and coordinates

raven kindle
#

ok

#

soo i just need to use code, i dont need to make any objects at all?

#

or i need only one, with the components

#

and script attached

#

but im just confused how i can tell the script that i want these 3 tiles, do i just use the tile name?

raven kindle
raven kindle
#

how can i do that?

rich adder
raven kindle
#

ah, and what do i put for L/M/R_piece?

rich adder
raven kindle
#

the name?

rich adder
#

wdym the name ?

raven kindle
#

of the tile

rich adder
#

no you dont use names.. you use the reference

raven kindle
#

where do i find that

#

from the tilemap?

raven kindle
#

soo i need a gameobject to drag

#

into the target transform

rich adder
#

not even close no

#

learn how to distinguish between variables and types

raven kindle
#

ok

#

but what is he dragging into the target transform?

#

the tiles he wants to use?

rich adder
raven kindle
rich adder
#

Transform is the type. inconsequential to what i've been telling you

#

the example I sent uses Tile instead of Transform

raven kindle
#

but they are dragging target into this box, what is target?

rich adder
#

thats why i said you have to learn the basics on declaring a type

raven kindle
#

the tiles?

rich adder
raven kindle
#

yes, but what does it contain

rich adder
#

anything you drag into it ?

#

have you played a shape game before ?

If you have a cube you cannot put a Sphere in it

#

the concept is the same

#

the type is the "shape"

#

again, if this confuses you its because you lack the basic c# understanding

#

you should not skip that

raven kindle
#

ok

frosty lantern
#

So I have this script calling my ui

private void OnTriggerEnter2D(Collider2D otherCollider){
        string playerTag = otherCollider.gameObject.tag;
    if(playerTag == "Player" || playerTag == "Player2"){
                if(userInterface != null){
                int playerId = (playerTag == "Player") ? 0 : 1;
                    userInterface.AddPoints(playerId, pointsWorth);}
                Destroy(gameObject);
}}}```
and my ui is
https://gdl.space/lecajivupo.cs
My ui's addpoints method, specifically:
```cs
  numberLabels[1].text = scores[playerNumber].ToString(); //with one player, the score is on the right

Is returning a null reference error.

#

I don't understand whet exactly it's trying to add points to, if not an array of values in the ui, which is already declared and instatiated. i'm not sure what other reference it should be looking for

rich adder
frosty lantern
rich adder
frosty lantern
#

do i need to declare the specific numberlabels 1 inside of the array?

#

how do i add a text component?

rich adder
frosty lantern
#

they just kindof write it as an overlay in game view

rich adder
#

do you have a custom inspector for this ?

#

seems to be missing a few things

#

do you have any compile errors ?

#

example, where are public GameObject statsPanel, gameOverPanel, winPanel; fields?

ivory bobcat
#

Make sure to save.

frosty lantern
#

how do i turn off the custom

rich adder
#

wdym URP comes with custom inspector lol

rich adder
#

screenshot console window

polar acorn
ivory bobcat
#

If you've got an error, the script inspector will not reflect the latest changes.

frosty lantern
frosty lantern
ivory bobcat
#

Not referring to runtime errors.

rich adder
#

might be related

#

Playground URP Asset

frosty lantern
rich adder
#

ohh

#

Unity Playground is Unity’s first project dedicated to total beginners, educators and anyone looking for an initial introduction to game development in a more simplistic form.

#

maybe it is gimped

frosty lantern
#

completely
but my assignment requires me to import assets and i'm kind of locked in due to deadlines

rich adder
#

well if you can't use inspector fields then i dont see how you would add the appropriate components in the slot

frosty lantern
#

so i'm hoping to get arroung the errors that honestly shouldn't even be there

rich adder
#

the errors is because ur trying to use components that have no references

frosty lantern
#

is there a way to turn off the custom inspector?

rich adder
#

it doesn't know what numberLabels[?] s

rich adder
polar acorn
#

Have you changed the script at all?

frosty lantern
polar acorn
#

So that can't be the one giving the error

rich adder
#

extra line

polar acorn
#

Ah, right, nevermind then

frosty lantern
#

i thought i could format the thing

#

like how discord does

rich adder
#

the line is numberLabels[1].text = scores[playerNumber].ToString(); //with one player, the score is on the right

#

numberLabels[x] isn't assigned because none of the fields are in the inspector pikachuface

rich adder
frosty lantern
#

i went and found the thing that sets the default inspector but it doesn't change it either

#

at the bottom

polar acorn
frosty lantern
#

alright

#

done

ivory bobcat
#

Do you've got any non-runtime errors?

frosty lantern
#

no

rich adder
#

indeed no script errors, tried it in my IDE

frosty lantern
#

i have another runtime error about some vfx but it's not affectingameplay g

ivory bobcat
#

It seems as though lines 19 through 26 are private

rich adder
#

yeah its weird af

#

try adding script again or right click and hit reset ?

#

maybe it serialized private idk lol

#

or perhaps compiling needs to be forced in Project Window by Right Click and hit Reimport

#

it did happen a few times for me on 2022. I save a script but never triggered the reload

frosty lantern
#

wereé reimport?

rich adder
frosty lantern
#

that didnt work

rich adder
#

🤷‍♂️ try this script another blank project

ivory bobcat
#

Is the script saved?

frosty lantern
#

yeah

polar acorn
#

Check section 5

#

Do you have those tags on your objects? I think the inspector script is likely doing a findWithTag and setting the values on this script

frosty lantern
#

yeah my object is a collectible and my player is set up how they say

polar acorn
#

Hm, I wonder if there is a UI prefab you're supposed to use entirely, rather than putting this script on something manually?

frosty lantern
#

yeah it's saved in prefabs

#

that's what i'm using

polar acorn
#

Do any of the playground components have custom inspectors?

frosty lantern
#

i tried turning the playground off because it says it will turn off the custom inspectors but i still don't see the fields

polar acorn
#

For example, do you see this for your auto rotate?

quiet pasture
#

does anyone know why dragging prefab into scene makes it,and all children invisible?

polar acorn
#

I just want to make sure it's loading those inspectors

polar acorn
ivory bobcat
quiet pasture
#

where should i ask them sorry

rich adder
quiet pasture
#

ok,thank you

polar acorn
#

Okay so the inspectors are loaded. It should be showing those fields if they were meant to be set by you

frosty lantern
#

so how do i fix the null reference error?

#

do text arrays already have a text component?

ivory bobcat
#

It's just an array that references instances somewhere.

frosty lantern
#

so how do i ensure that it is getting the reference?

ivory bobcat
#

Unfortunately, it seems as though you aren't supposed to be modifying the arrays through the inspector.

rich adder
#

yeah this is an odd one

#

why would they gimp the inspector like that

ivory bobcat
#

So either you're supposed to set them up during runtime or something from the scene is missing.

#

Maybe set a break point and see the contents of the collection.

frosty lantern
#

all i have is the player, ui prefab, and an object with a collectible component

ivory bobcat
#

Or log the contents

frosty lantern
#

how do I do logging and break points?

rich adder
#

maybe you can do
numberLabels = FindObjectsOfType<Text>(); 😬

rich adder
#

custom inspector!

polar acorn
#

It doesn't do anything with that references section so something else must be setting it

rich adder
#

well it doesn't bring the fields though

polar acorn
#

Is there a "search all files" in GitHub or am I gonna have to pull this

polar acorn
rich adder
#

yeah its odd that they would put that in another editor script

#

i guess it comes at a later time ?

#

not sure what the thought process was here

frosty lantern
#

should i check those?

polar acorn
#

Yes, check those 11 references, see if you can find what sets numberLabels

raven kindle
#

@rich adder i watched all guides

polar acorn
#

The 1 asset reference is the prefab you are currently using so no need to check that

raven kindle
#

but it didnt really help

rich adder
raven kindle
#

the one u sent

simple forge
rich adder
#

i wish had the doubt emoji

raven kindle
#

:(

rich adder
#

i sent a whole course on c# + unity

#

not 1 vid

simple forge
raven kindle
#

yes i went through the whole course

rich adder
raven kindle
#

yes

#

it didnt help tho

#

just basic c# stuff

glad igloo
#

can someone please explain to me what the problems at the bottom mean, i just got the latest version of unity

rich adder
#

then you didnt really watch them

raven kindle
#

oh i did

rich adder
#

no you skimmed through it

#

i can tel

raven kindle
#

it helped abit, but not what i need to do

rich adder
#

no one finishes such important concepts in less than an hr

sonic remnant
raven kindle
#

i skimmed the loops/if statements etc

rich adder
sonic remnant
#

can someone please help me? im stuck for a day now ..

simple forge
polar acorn
#

Unity Playground Ghost References

languid spire
frosty lantern
#

these seem to be attatched components, not sources for the text

#

maybe that's why it's null, it's literally not created

#

idk

sonic remnant
hollow dawn
#

should i use visual studio code for coding c# in unity? im a beginner which one is the best to use?

raven kindle
#

@rich adder so i found out the thing i drag into the script is a tilemap

raven kindle
#

but when making a new tilemap, do i just paint one tile there and drag it

#

or how can i do it

rich adder
#

moving tiles aren't easy in tilemap

#

you would have to move the entire tilemap just for 1 platform

raven kindle
#

yes thats what i thought

#

how would i do it then?

rich adder
#

why do you want to use tilemap in the first place?

raven kindle
#

what else would i use?

rich adder
#

you can just make LMR a combined object prefeb

sonic remnant
#

@languid spire do you understand my problem better now?:) i really can't figure out the solution.

raven kindle
#

ok

polar acorn
rich adder
#

tilemap is better for building levels with tiles

#

or grids

simple forge
rich adder
simple forge
#

ive checked that the function gets called

#

deleted and rebaked my navmesh a couple of times

rich adder
grim eagle
#

yo

#

am i allowed to send a youtube vid here which is pretty usefull for complete beginners

frosty lantern
#

cool thanks

rich adder
simple forge
languid spire
sonic remnant
#

hahaha, jonge ik loop godverdomme al een hele dag te kutviolen.

languid spire
grim eagle
rich adder
sonic remnant
#

everyone here can read dutch but can someone please help me with my problem 🥲 ...

buoyant knot
#

ist wunderbar?

languid spire
#

there is way too much of it, you will have to narrow it down and show some log output

simple forge
grim eagle
rich adder
simple forge
#

wait no, walk point isnt needed for the chase player function

#

only patrolling

rich adder
#

yea

#

if its not moving in start you have to select the agent in playmode with navmesh selected and screenshot it

simple forge
#

i decreased the sight range and attack range to check if it would patrol

rich adder
buoyant knot
rich adder
simple forge
raven kindle
#

@rich adder How can i make the platforms as an object? When i drag the asset on the hierarchy nothing happens

rich adder
# simple forge

are you sure that agent type is assigned to walk on that Navmesh layer ?

simple forge
#

well i havent used unity AI before so if you could explain how id go about checking ?

rich adder
#

you need to lay 3 side by side and put 1 box collider @raven kindle

#

the parent object should be the middle tile one ideally

simple forge
#

heres the nav mesh surface

raven kindle
#

One game object for each tile?

rich adder
median escarp
#

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

public class MonsterMovement : MonoBehaviour
{
public Transform[] patrolPoints;
public float moveSpeed;
public int patrolDestination;

// Update is called once per frame
void Update()
{
    if(patrolDestination == 0) 
    {
        transform.position = Vector2.MoveTowards(transform.position, patrolPoints[0].position, moveSpeed * Time.deltaTime);  
        if(Vector2.Distance(transform.position, patrolPoints[0].position) <.2f)
        {
            global::System.Boolean v = patrolDestination
                == 1;
        }             
    }
    if(patrolDestination == 1) 
    {
        transform.position = Vector2.MoveTowards(transform.position, patrolPoints[1].position, moveSpeed * Time.deltaTime);  
        if(Vector2.Distance(transform.position, patrolPoints[1].position) <.2f)
        {
            global::System.Boolean v = patrolDestination
                == 0;
        }             
    }
}

} @languid spire

sonic remnant
eternal falconBOT
raven kindle
#

ok

buoyant knot
raven kindle
#

Like this?

rich adder
median escarp
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonsterMovement : MonoBehaviour
{
    public Transform[] patrolPoints; 
    public float moveSpeed; 
    public int patrolDestination;


    // Update is called once per frame
    void Update()
    {
        if(patrolDestination == 0) 
        {
            transform.position = Vector2.MoveTowards(transform.position, patrolPoints[0].position, moveSpeed * Time.deltaTime);  
            if(Vector2.Distance(transform.position, patrolPoints[0].position) <.2f)
            {
                global::System.Boolean v = patrolDestination
                    == 1;
            }             
        }
        if(patrolDestination == 1) 
        {
            transform.position = Vector2.MoveTowards(transform.position, patrolPoints[1].position, moveSpeed * Time.deltaTime);  
            if(Vector2.Distance(transform.position, patrolPoints[1].position) <.2f)
            {
                global::System.Boolean v = patrolDestination
                    == 0;
            }             
        }
    }
}
rich adder
languid spire
buoyant knot
#

@sonic remnant It’s just kind of hard to navigate your code because there is so much. I recommend using #region and #endregion directives to organize it

grim eagle
#

that looks so complicated yet it is beginner 😭

median escarp
eternal falconBOT
raven kindle
median escarp
buoyant knot
#

@sonic remnant Example
#region Modify quickslots
AddToQuickSlot
RemoveFromQuickslot
FindNextOpenQuickslot
#endregion
#region Selecting Quickslot
SelectQuickslot
DeselectQuickslot
#endregion

etc

rich adder
#

for navmesh agent

digital lynx
#

hello, so i followed the code in the following video. However the character controller doesn't want to jump. Any idea why?

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

public class ThirdPersonMovement : MonoBehaviour
{

    //required
    public Transform cam;

    CharacterController controller;
    float turnSmoothTime = .1f;
    float turnSmoothVelocity;
//movement
    Vector2 movement;
    public float walkSpeed;
    public float sprintSpeed;
    float trueSpeed;


    //jumping
    public float jumpHeight;
    public float gravity;
    bool isGrounded;
    Vector3 velocity;   

    void Start()
    {

(Part 1)

rich adder
simple forge
sonic remnant
raven kindle
buoyant knot
#

i’m trying, but it’s a big system lol

raven kindle
#

didnt place them

languid spire
#

!code

eternal falconBOT
rich adder
#

*Large Code

median escarp
#

@languid spire works now thank you so much man

buoyant knot
#

I think this would have been simpler if you had split your EquipSystem and a Quickslot class

rich adder
languid spire
median escarp
#

will do thank you so much guys

digital lynx
rich adder
#

if its anything like earlier you probably mised a step

#

again

#

"followed the code" is quite common here and never turns out it is

raven kindle
#

@rich adder also they dont seem to inherit properties, i change sorting layer for parent and the child ones dont change

#

or do i have to do it manually for each one?

buoyant knot
#

@sonic remnant One more thing that helps in terms of style is documentation (docstrings).
Right before a method, write:

public void AddItemToInvenyory(Item item) {```
#

then if you mouseover the function from anywhere in your program, it will give you a tooltip that gives you that string

#

which is immensely useful. VS’s IDE automatically adds the <summary> if you write /// before a method like that

rich adder
raven kindle
sonic remnant
#

@buoyant knot thanks for the tip, i will structure it and hope i will solve it ❤️

buoyant knot
#

i know i’m not directly solving your problem, but I think these are handy tools as you grow out

rich adder
buoyant knot
#

a lot of my older code doesn’t have these features, which makes it harder to read now.

raven kindle
#

ok

rich adder
#

they are not classes

#

gameobjects

raven kindle
#

yep

sonic remnant
#

understandable. @buoyant knot do you think when i structure it you can solve it for me?

raven kindle
#

and now i can link this game object parent to the script right?

rich adder
rare basin
buoyant knot
#

not sure lol

rare basin
#

if someone solves it for you

rich adder
#

and spawn one from folder not the ones from scene @raven kindle

raven kindle
#

ok

#

i just drag it yes

#

to folder

rich adder
#

yes

raven kindle
#

cool cool

sonic remnant
#

okay @rare basin but maybe when i understand the problem why its not working then i learn from it. right?

raven kindle
#

now to figure out how to make it show

#

when i generate it

rare basin
summer stump
rich adder
raven kindle
#

easier said then done :)

#

for me at least

rare basin
#

it's hard to point you in proper direction without basic knowledge

raven kindle
#

ty

sonic remnant
#

okay man, just want to understand it and learn from it. im trying to solve it for a day now. so thats why i ask it. i do the best i can..

buoyant knot
#

@sonic remnant right, one more tool that is very useful is assertions. write Debug.Assert(somethingThatShouldBeTrue, “Error message if it isn’t.”)

rich adder
rich adder
digital lynx
orchid trout
#
        private void MoveLine()
        {
            transform.localPosition = new Vector3(0f, _linesAnchor.x, _linesAnchor.y);
            Vector3 iterativeVec = transform.localPosition;
            if (lines != null)
            {
                for (int i = 0; i < lines.Length; i++)
                {
                    if (isStart)
                    {
                        lines[i].SetStartPoint(iterativeVec);
                    }
                    else
                    {
                        lines[i].SetEndPoint(iterativeVec);
                    }
                    iterativeVec.z += _lineSpacing;
                }
            }
        }
        public void SetStartPoint(Vector3 start)
        {
            _startPoint = WorldToLocal(start);
            SetPoint();
        }   
        public void SetEndPoint(Vector3 end)
        {
            _endPoint = WorldToLocal(end);
            SetPoint();
        }

        public Vector3 WorldToLocal(Vector3 worldPosition)
        {
            return transform.InverseTransformPoint(worldPosition);
        }

What are possible reasons why when I set this position to a position that the positon I set it to is miles away from where its supposed to be?
I am using InverseTransformPoint to do world -> local but the values that get assigned are completely wrong and I am not sure why

rich adder
orchid trout
#

whoops wrong image

buoyant knot
#

these lines get removed when you build, but give you error messages if the expression is false. I would do things like,
Item item = GetComponent<Item>();
Debug.Assert(item != null, “No item component found!”);

summer stump
digital lynx
buoyant knot
#

you should use a large number of Debug.Assert statements throughout your code to detect fuckups as early as possible

rare basin
orchid trout
raven kindle
#

unity crashed :) and is using 8gb ram wtf

#

i think it generated 1000000s platforms

frosty hound
#

That woud likely be the result of an infinite loop

raven kindle
#

yup

#

none of my heirarchy saved ...

#

why is that?

rich adder
#

because u never saved the scene

#

and it crashed before you did

buoyant knot
# digital lynx how to do that?

example before:

itemList.Add(item);
}

Better style:

public void AddItemToInvenyory(Item item) {
Debug.Assert(item != null, “Can’t add a null item to our inventory!”);
inventoryList.Add(item);
}```
raven kindle
#

fuck

rich adder
buoyant knot
#

he asked a separate question in a void about assertions

rich adder
#

yea true, think they thought you were replying to theirs

buoyant knot
#

probably lol

rich adder
#

anyway @digital lynx have you tried Debug.Log(isGrounded) ?

#

still didnt answer lol

digital lynx
#

i don't even know how

raven kindle
buoyant knot
rich adder
rich adder
raven kindle
#

yup

rich adder
#

best Task End

#

also not recommended you run unity as Admin btw

buoyant knot
#

Out of Memory exception ☠️

raven kindle
#

i couldnt fix it

#

i did spend a while trying

#

when i click restart as standard user nothing happened

rich adder
#

are you running custom win 10/11 ?

raven kindle
#

maybe

rich adder
#

could be user extra elevated permissions

#

throws unity off when UAC is disabled

raven kindle
#

probably is that

#

its not custom os but optimized one

rich adder
#

yeah that would be custom , like Tiny7 etc

#

part of the "optimization" was probably turning off UAC altogether and/or elevated admin user

raven kindle
#

its not the update function

queen adder
quasi rose
languid spire
rich adder
#

your if condition probably never goes false

raven kindle
#

i need to make it so it updates after the player moves over one?

simple forge
amber spruce
#

how do i load a specific scene?

rich adder
rich adder
amber spruce
rich adder
amber spruce
#

forgot it needed the "

rich adder
#

and not needing ""

amber spruce
#

all it is is the main menu where you choose single or multiplayer

rich adder
#

private const string MyCoolScene = "SinglePlayer";

#

SceneManager.LoadScene(MyCoolScene);

raven kindle
#

@rich adder Which one do i need to select?

rich adder
raven kindle
#

oke

simple forge
#

i still need help with AI, i was just adding scene restarting in the meanwhile

raven kindle
#

@rich adder i managed to stop it quickly after running, it made platforms but lots of things on hierarchy

#

how do i fix this?

#

there is probably 1000+ things on the hierarchy

#

its generated the platforms ontop of each other loads

rich adder
# raven kindle

you're spawning Clone of Clone indicates some sort of Recursive spawning or something

#

find a better way to do this

#

plenty of tutorials on these infinite platform things

simple forge
#

they're moving

#

idk why

safe root
#

Why is this Object reference not being set?

rich adder
eternal falconBOT
safe root
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace TowerDefense
{
    public class Grids : MonoBehaviour
    {
        private Dictionary<Vector3Int, GameObject> gameObjects = new Dictionary<Vector3Int, GameObject>();
        

        public bool Add(Vector3Int tileCoordinates, GameObject newgameObjects)
        {
            if (gameObjects.ContainsKey(tileCoordinates)) return false;
            Debug.Log("Wo");
            gameObjects.Add(tileCoordinates, newgameObjects);
            return true;

        }
        
        public void Remove(Vector3Int tileCoordinates)
        {
            if (!gameObjects.ContainsKey(tileCoordinates)) return;

            Destroy(gameObjects[tileCoordinates]);
            gameObjects.Remove(tileCoordinates);
            Debug.Log("Work");
        }

        public static Vector3Int WorldToGrid(Vector3 worldPosition)
        {
            Grid grid = FindObjectOfType<Grid>();
            Debug.Log(grid);
            Vector3Int gridPosition = grid.WorldToCell(worldPosition);
            Debug.Log("Wor");
            return gridPosition;

        }

        public static Vector3 GridToWorld(Vector3Int gridPosition)
        {
            Grid grid = FindObjectOfType<Grid>();
            Debug.Log("W");
            Vector3 worldPosition = grid.GetCellCenterWorld(gridPosition);

            return worldPosition;
        }
    }
}
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace TowerDefense
{
    public class Path : MonoBehaviour
    {
      
      [SerializeField] private List<Vector3> points = new List<Vector3>();

      void Start()
      {
        CollectPoints();
      }

      private void CollectPoints()
      {
        points = new List<Vector3>();
        Grids grid = FindObjectOfType<Grids>();

        for (int i = 0; i < transform.childCount; i++)
        {
            GameObject child = transform.GetChild(i).gameObject;
            Vector3 point = child.transform.position;

            points.Add(point);
            grid.Add(Grids.WorldToGrid(point), child);
            child.SetActive(false);
        }
      }
    
    }
}
rich adder
#

*Large Code

safe root
#

Oh

#

My bad

#

How do I send it to you?

#

Send it in here

rich adder
#

hit save and send the link

safe root
#

((BRB, going to lunch))

rich adder
#

nvm its the slash at end

#

grid is Null apparently

#

you'd have to show the Grid gameobject inspector

thin sedge
#

Hi! I'm trying to use an OnCollisionEnter method to enable an animation for a start point in a platformer game. The arrow is supposed to swing back and forth when the player runs by it and when the animation is complete, the animation should be disabled again. How do I do that?

#

I have no code whatsoever other than an empty method

quiet dune
#

Hi, I'm trying to rotate a GameObject (which is stretched along a surface) away from the surface by using its RigidBody and setting rb.rotation = x. I'm assuming the RigidBody rotates around the center of mass? It seems like the rotation isn't working, because parts of the GameObject are pushed into the surface due to the rotation and preventing the rotation. The Physics Debugger shows forces that support this assumtion. Is there a way to force the rotation and make is push the GameObject away from the surface? Or any other ideas how to deal with this?

thin sedge
rich adder
#

nothing forcing you to use that one lol

thin sedge
rich adder
#

ok so dont use it

celest holly
#

Hi, My visual studio isnt working, apparently its something to do with the "miscellaneous files" at the top left. Can anybody help?

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

celest holly
#

thank you

frosty lantern
#
        public static void Create ()
        {
            ScreenFader controllerPrefab = Resources.Load<ScreenFader> ("ScreenFader");
            s_Instance = Instantiate (controllerPrefab);
        }

This code is trying to set up a controller in (https://gdl.space/vohaxonuni.cs)
and returning a null error

#

well nevermind

celest holly
frosty lantern
#

it was a teleporter that i'm not using anymore

#

because it didn't work

dense root
#

so I'm trying to set a timer that delays the launch of the ball by 3 seconds, where do i set the method to avoid the ball jittering like so?

    public float targetTime = 3.0f;
    
    // Start is called before the first frame update
    void Start()
    {
        startPosition = transform.position;     
    }

    void Update()
    {
        targetTime -= Time.deltaTime;
        if (targetTime <= 0.0f)
        {
            Launch();
        }
    }

    public void Reset()
    {
        rb.velocity = Vector2.zero;
        transform.position = startPosition;
        Launch();
    }

    private void Launch()
    {
        float x = Random.Range(0, 2) == 0 ? -1 : 1;
        float y = Random.Range(0, 2) == 0 ? -1 : 1;
        rb.velocity = new Vector2(speed * x, speed * y);
    }
#

Oh

#

I only need to call launch once

#

But how do I do so?

celest holly
#

maybe you could use a boolean

#

to check if its been launched already

dense root
#

ahh that's a good idea let me try that

rich adder
dense root
#

Hmm what's causing my ball to be stuck?

#
    void Start()
    {
        startPosition = transform.position;     
    }

    void Update()
    {
        targetTime -= Time.deltaTime;
        if (targetTime <= 0.0f)
        {
            if (Launched = false)
            {
                Launch();
            }
        }
    }

    public void Reset()
    {
        rb.velocity = Vector2.zero;
        transform.position = startPosition;
        Launch();
    }

    private void Launch()
    {
        float x = Random.Range(0, 2) == 0 ? -1 : 1;
        float y = Random.Range(0, 2) == 0 ? -1 : 1;
        rb.velocity = new Vector2(speed * x, speed * y);

        Launched = true;
    }
rich adder
#

basic c# mistake 🙂

#

= is assigning == for checking equality

dense root
#

Oh goodness

#

Thanks haha :)

#

I forget... in PONG after the play scores do the paddles reset too?

edgy prism
dense root
#

they don't but the game is ALOT faster

#

Paddles are dinky too

rich adder
#

yeah paddles never did reset

#

that would feel terrible gameplay wise

safe root
rich adder
edgy prism
#

Oop my bad I thought they did

safe root
rich adder
safe root
rich adder
quiet dune
safe root
rich adder
#

its ok to guess

#

How did you setup/paint these tiles btw ?

safe root
safe root
rich adder
#

FindObject -=> Scanning through all the scene objects

#

OfType <T>

#

T in this case is the component of Grid.

#

do you have a Grid component in the scene

#

in C# you're mainly working with types not Names ideally

safe root
rich adder
#

yeah its built into unity

#

thought thats what you used to lay tiles

safe root
#

Oh, that makes a lot more sense

rich adder
#

your code uses functions from it

#

did you copy and paste this without understanding it ? lol

safe root
#

No, I followed a video in my class and it told us about this stuff but never told me about that

#

From Mastercoding

rich adder
#

either you skipped a step or its a bad course

safe root
#

I don't think I did and it's good as they are fixing stuff constantly but they still need feedback

rich adder
safe root
dense root
#

How do I wire this timer to show in the UI/UX?

rich adder
#

same thing as always

#

make a reference, use the value

dense root
#

Like I have a TMP text object and I want it to show the countdown

rich adder
#

dont make a timer inside a ball tbh

thin sedge
#

How do I write the if statement for if the player tag is in the collider again?

#

I am too tired to think right now

thin sedge
#

the "other" is somehow wrong in vs and is marked red whenever I write it

thin sedge
rich adder
thin sedge
#

I didn't know it needed a value?

#

here's the whole script:

edgy prism
thin sedge
rich adder
thin sedge
rich adder
#

side effect of blindly copying code

rich adder
thin sedge
#

So it needs the collider as reference?

rich adder
#

a collider 2D stored in collision

#

the collider is stored in collision

polar acorn
thin sedge
#

And when the animation finishes should be able to do it again

thin sedge
polar acorn