#💻┃code-beginner
1 messages · Page 79 of 1
The Input should be in Update, only movement in FixedUpdate
Oh, wait. It's in both?
Getting continuous input is totally fine in FixedUpdate
That's a common misconception
sorry, i just fixed that
Because one-time inputs like GetKeyDown will work poorly in FixedUpdate
Ok, good to know
Ah, makes sense
You still set velocity in both
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
Yeah, but that would be for continuous only, right?
That does make sense
Yep, continuous only.
Surprisingly I have never heard anyone else mention it, kinda figured it out on my own🤔
I'm such a pioneer
{
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;
}
}
}
does this look right?
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
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
To Update, right?
yes
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
hows this
Remove the rb.MovePosition line. You are already moving the rb with velocity
I wasn't talking about the code in the top. Change the name back to movePos.
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
Looks better, try it out
You probably need to make speed higher now that you removed the MovePosition line
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?
It really looks like another script is changing the flipX too. It shouldn't behave like this
Or maybe an animation is changing it
You'll need to incorporate the stopping logic into the script code.🤷♂️
Is it async? A coroutine? Or just an update that runs in the editor?
I am trying out wave function collapse to generate terrain randomly
just regular for loop and recursion
Well, that would just freeze the editor while it's executing. And you can't stop it from the outside.
Ah so I have to force quit then
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.
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
Thanks will check it out. I didn't think visualizing it was possible after searching in google but this gave me something to read about
Do you mean editing in Visual studio or something else?
I think by just removing the if(x < 0) { sr.flipX = false; } else if (x > 0) { sr.flipX = true; } itll fix it but I was hoping for the rest animation to be looking right after moving right instead of left
Are you using a joystick/controller?
keyboard but I do plan on using controller in the near future
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
And you earlier showed code where you were only setting flipX to false but it was still flipping it. That's what makes me think that another script or animation is doing something.
Ok will check it out
And to make your code execute asynchronously, yes, you need to write it in an async way(async/coroutine).
ah
So you mean to write this as an editor coroutine and have a method to stop execution if i need to as well
well the only other script I have is a script that allows the sprite to billboard when ever the camera moves
Yes.
For testing purposes, change it to: cs if(x < -0.5f) { sr.flipX = false; } else if (x > 0.5f) { sr.flipX = true; }
And tell me if it changes anything
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 /* */
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?
See? Something else is flipping it.
Do this:
- Use your code editor to search the scripts for
flipX - Check the animations that you are using and see if they are modifying SpriteRenderer.flipX
the falling platform doesnt detect my character for some reason
Something missing in the setup. It could be many different causes.
Well, how does it detect the ground?
Another important one @flint wind:
3. Check if anything is modifying your player's transform.localScale
Including the animations
do you have trigger?
this what in the code i had the tag alr on the character
yes
OnCollision doesn't work with trigger
what usually best one for the falling plat?
put trigger a bit above it in a separate object
then disable the main solid collider when you enter trigger
What exactly is "falling plat". You'll need to make it clear for us to understand as we don't know anything about your project.
im making obstacle course
That doesn't make it much clearer.
Falling platform or a platform that you can fall through?
Falling platinum?
making like a wipe out game for assignment
platform
What should happen when the platform hits you?
And is it really a platform, or just solid?
it should disappear when being stepped in
Ah now I see. I was also thinking something different
You should just say that in the first place
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.
Like a block that falls when you step on it, right?
I think they mean a game like obstacle course like fall guys or w/e
I think I see my problem. In the animator window I have the rest sprite originally looking left. I guess what im looking for is how to flip the x of the rest sprite after moving right
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
I did check through all my components and nothing modifies the x of the sprite
3 steps
That's just one step, or two, depending on what you mean with "x" of the sprite
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
Doesn't sound code related - but sounds like perhaps you are accidentally using a perspective camera in your 2D game.
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
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
Yeah I have a basic script made for parallax scrolling but it doesn’t seem to work when I set the camera to Orthographic
then you have an issue in your script
Ahh okay. Tyty. Just having a lead on where the problem exists is nice. I’ll start poking around in there
Would you mind looking over my script if I post a pic?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
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 😍
have you got it working?
I fixed my problem, thank you to urs and A.. help
i also have another issue
its with my billboard script
you don't have a MainCamera in the scene
Something on that line is null, it has to be Camera.main.
Your camera needs to have the "MainCamera" tag
Yup that fixed it, thank you!
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.
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
here is how the weapon hold looks (image 1), the gun it looks the same , like when it's spawned, the roation is all zero.
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
it works thank you very much
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
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.
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.
what exactly do you need help with
what have you done so far
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
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
okay thank you, do you have any examples or videos to recommend for this?
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
thank you
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
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.
Because it references something in the scene, and it's not in the scene anymore. You can reference something inside the prefab.
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.
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.
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?
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.
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?
what exactly are you trying to do
I didn't think about it like that. And I'm not using a manager yet, so. This answers my question.
most the time, people want something and they don't realize what they want isn't what they need
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
Some kind of Init method
Apparently, things are more specific and require more thought than I had expected. Which is fine. We live and learn.

How do i make a firework rocket like in Firework mainia??
Don't crosspost.
ask ChatGPT
Oh you removed it in the other channel, nevermind then.
We don't know what's firework mainia, so you'll need to provide some more info.
On the topic of a Manager. How would I do it? Just a scriptable object to store the info, then reference the manager though the weapon script? So it goes Weapon script --> Manager --> Player as a link?
My grab script is what allows me to pick up (and by extension, drop) weapons.
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
so with what exactly do you have issue
what have you done so far
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.
share some code
in fact using any Find() type method is a bad practice in my opinion and you never really need to use them with proper architecture
correct me if im wrong, these functions no need to exist, atleast for me
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
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.
so what exactly do you have problem with
you are asking such general questions
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.
I've been porting a game once to xbox, and we got a project with like nested for loops with Find() looking for objects by string in Update()
it didin't even run
Yeah, that's sounds terrible.
it was funny tho xD
That is there is no like physics like if it turns sideways it still shoots up and the firework if i put a slope about it wouldnt like turn
well, you need to implement it
Yea idk how
show the code you've done so far
its a VFX graph
this is a code related channel
true
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
Thanks i will take a look and i asked in VFX and Particles
example of how I use scriptalbe objects
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.
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.
Well you just need a refrence to the scriptable object then take the data from the scriptiable object. That is all.
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.
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.
I love how the two of you help me understand this more than 97% of the tutorials I've watched and in less time 😆
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
Because instantiating would cause performance issues right?
It saves performance and reduces garbage collection
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
Those are my enemies btw.
They are all made by 1 enemy prefab. But I take enemy scriptable objects to replace their sprites at runtime.
you can use them much better btw
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
i only have attack and hit audio though, and it's only attack and hit vfx
but i can see that
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
i don't have issues currently
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
yea i've done this before. idk if i should do that in this game. it's good for like open world survival games. This is just arcade game.
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
so you think I should have more S.O. for 1 weapon even if I'm just using what I told you?
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
yea haha, so true
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?
What have you done so far?
Show the code
And what exactly do you have an issue with
I've only added the animation and the collider to the object
So no code
this is a code related channel
Right...
I'll take it somwhere else then
how i set VideoClip on run time?
i tried
1- Why did you leave off the ; on both lines
2- What's the error? Mouse over the red lines -> read the error
oh, so that is .clip @@ , ty
it is configured
right
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?
what have you done so far and what exactly do you need help with
Linking the script with the right tile on a tilemap
you gave 0 context of how this should work
and what have you done so far and what do you need help with
I've a base SO for most assets, but broken into like VFX and other project related assets, but otherwise this base SO does most of the heavy lifting. Composition approach best approach.
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
Hello, is there a way to make the object not jump multiple times when collided to the walls
make grounded check better
I did that but...
show code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
mate if you're not willing to share the code lookup how to make grounded check better
In this part, we will take care that our player can only jump while he is standing on the ground.
Github repository:
https://github.com/codinginflow/2DPlatformerBeginner
🎓 Learn how to build a 2D game in Unity (beginner): https://www.youtube.com/playlist?list=PLrnPJCHvNZuCVTz6lvhR81nnaf1a-b67U
🎓 Learn how to build a 3D gam...
Here you go
isGround.collider_collision_interact
doesn't show what this does
It returns true or false by using
Oncollisionenter2D
yeah this wont be a suitable way to do it , guaranteed
r u checking for every platform to see wich one is the player touching?
lol
check out the video I've sent. They do this properly use physics casts @short grove
Ye
It was intentional
Ok
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"
I should use arrays?
no arrays got nothing to do wtih it, you need physics queries
in this case I've sent a boxcast vid
think of it like an invisible box thats gets thrown in the direction you pass it , tells you anything thats hit in box
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
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?
why are you crossposting this everywhere..
i am crossposting nothing everywhere.
I don't know why it would change, but make sure the scriptable object asset is of the extension .asset
you posted in multiple channels , thats crossposting bozo
oh nooo that is so horrible
2 channels
how about you find some hobbies instead of getting angry at people who post in 2 channels because they are not sure which channel it belongs to
how about you follow community rules instead of acting like an entitled brat
i am quite sure calling people entitled brats is also against the #📖┃code-of-conduct buddy
If you're not sure what channel to post in, just throw it in general in the future (it moves slower anyway). As for the question, you can consider using scriptable objects and sticking them onto a singleton class that lives on the scene (which you DDOL between scenes). This way you can access your cache'd data directly if you're having problems passing references around/
Static class should be fine too honestly if it's just data
then populate it on start, many ways you can go about it
ok thank you 🙂
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.
wdym extract game as exe?
if a game is built out on windows platform it should have a bunch of files and an exe to start the game?
it seems that this problem is on XR settings?
I don't know, I just clicked on build. and I wanted to have one file to send to someone.
thats called build, u dont extract the game, u build out the game app
screenshot consolewindow
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);
}
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hmm screenshot the entire window
clear all the logs and Build Again
@digital lynx
do you get actual errors?
only this warning
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);
}
}
}
what is line 26?
if you dont get errors then build should be fine
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
so where did you define cam ?
i was just following a youtube tutorial
follow it again but better
also configure your IDE(Code Editor)
its not underlining error?
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...
well you clearly did not follow it to the T
look at the top of his script and then yours
should configure your IDE !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
if I start the game it works normally but when I turn it off it throws this warning
this warning seems related to some third perty plugin
it shouldnt prevent a build afaik
ok thanks you one more thing where can I download JDK?
install it via the hub it gives you the correct version
Cog wheel icon on the editor Installs tab
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
like +=5
so this inscreases it by 5
numberOfEnemiesInWave += 5;
here??
k thanks
no the cog wheel on the installs
so there?? i dont know
this means you did not install unity via hub.
you'd hve to manually do it. also this is not coding question and should go in #💻┃unity-talk
I am very new, how can i assign a tile to a gameobject?
I will check thank you
create a field of type tile, assign it in inspector
I have made a tilemap, but how can i assign it in inspector
what are you trying to do exactly?
you haven't explain
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
thats not how tiles work
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
but i want to delete them after i use too
doesnt each platform need to be its own object?
no
irrelevant
You store the tiles positions to where they have been placed
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. 😕
but when i generate, how does it know which tiles to use?
and can i group multiple tiles together, so when it generates, it spawns 3 at a time?
you reference the tile and add it in the slot
public Tile SomeTile```
but how can i group mutlple tiles into one?
i have all the individual ones
i want these 3 to be joined
youd have to reference all three n combine them via code
oh
or just use a image editor and make it 1 piece
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...
ok
this isnt a tilemap
major differences
a tilemap is a self contained gameobject
with its own assets
and coordinates
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?
from here?
no you use the reference
how can i do that?
public Tile L_piece, M_piece, R_piece;
ah, and what do i put for L/M/R_piece?
what do you think
the name?
wdym the name ?
of the tile
no you dont use names.. you use the reference
not even close no
you should start here https://learn.unity.com/project/beginner-gameplay-scripting
learn how to distinguish between variables and types
what target transform
Transform is the type. inconsequential to what i've been telling you
the example I sent uses Tile instead of Transform
but they are dragging target into this box, what is target?
thats why i said you have to learn the basics on declaring a type
the tiles?
target is just a name
yes, but what does it contain
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
ok
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
one of these is null
numberLabels[1]
or
scores[playerNumber]
that should be where they are declared, right?
[Header("References (don't touch)")]
//Right is used for the score in P1 games
public Text[] numberLabels = new Text[2];
// Internal variables to keep track of score, health, and resources, win state
private int[] scores = new int[2];
the only thing that can be null is if numberLables doesn't have a Text componennt inside
do i need to declare the specific numberlabels 1 inside of the array?
how do i add a text component?
its a public serialized field, there should be slots in the inspector no?
I don't see it
they just kindof write it as an overlay in game view
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?
Make sure to save.
I think the urp just comes with a custom inspector that's so tied into everything that when theres an error it's half impossible for me to look through
how do i turn off the custom
wdym URP comes with custom inspector lol
did you actually save the script ?
screenshot console window
Why would URP come with a custom inspector for a class you made
If you've got an error, the script inspector will not reflect the latest changes.
i didn't make it it's the playground urp asset
Not referring to runtime errors.
whats that? I keep hearing the layer field is also missing for that
might be related
Playground URP Asset
yeah i didn't import the layer manage which fixed that error
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
completely
but my assignment requires me to import assets and i'm kind of locked in due to deadlines
well if you can't use inspector fields then i dont see how you would add the appropriate components in the slot
so i'm hoping to get arroung the errors that honestly shouldn't even be there
the errors is because ur trying to use components that have no references
is there a way to turn off the custom inspector?
it doesn't know what numberLabels[?] s
not sure how unity paints the inspector in that project
Have you changed the script at all?
no
Because the link you shared, line 75 is a curly brace
So that can't be the one giving the error
Ah, right, nevermind then
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 
pastebin sites already format the code 🙂
i went and found the thing that sets the default inspector but it doesn't change it either
at the bottom
That's entirely unrelated and you should probably put that back to what it used to be
Do you've got any non-runtime errors?
no
indeed no script errors, tried it in my IDE
i have another runtime error about some vfx but it's not affectingameplay g
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
wereé reimport?
that didnt work
🤷♂️ try this script another blank project
Is the script saved?
yeah
So, I found the tutorial I think is being used here. It looks like it depends on specific tags to set references:
https://learn.unity.com/tutorial/advanced-concepts?uv=2022.2&projectId=5c5147e8edbc2a002069444e#
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
yeah my object is a collectible and my player is set up how they say
Hm, I wonder if there is a UI prefab you're supposed to use entirely, rather than putting this script on something manually?
Do any of the playground components have custom inspectors?
i tried turning the playground off because it says it will turn off the custom inspectors but i still don't see the fields
For example, do you see this for your auto rotate?
does anyone know why dragging prefab into scene makes it,and all children invisible?
I just want to make sure it's loading those inspectors
not from this statement alone
Is it positioned in view of the camera
What do you mean by invisible? This is the programming channel btw.
where should i ask them sorry
ok,thank you
Okay so the inspectors are loaded. It should be showing those fields if they were meant to be set by you
so how do i fix the null reference error?
do text arrays already have a text component?
It's just an array that references instances somewhere.
so how do i ensure that it is getting the reference?
Unfortunately, it seems as though you aren't supposed to be modifying the arrays through the inspector.
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.
all i have is the player, ui prefab, and an object with a collectible component
Or log the contents
how do I do logging and break points?
maybe you can do
numberLabels = FindObjectsOfType<Text>(); 😬
custom inspector!
It doesn't do anything with that references section so something else must be setting it
well it doesn't bring the fields though
Is there a "search all files" in GitHub or am I gonna have to pull this
Right, they don't draw those fields so they obviously expect it to be coming from somewhere else, but where?
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
Yes, check those 11 references, see if you can find what sets numberLabels
@rich adder i watched all guides
The 1 asset reference is the prefab you are currently using so no need to check that
but it didnt really help
"all the guides"
the one u sent
i wish had the doubt emoji
:(
what did i sent?
i sent a whole course on c# + unity
not 1 vid
i am current making AI for my game, the navmesh is baked and look fine, but my enemies still wont move
yes i went through the whole course
you finished all these ?
#💻┃code-beginner message
i followed this tutorial
https://www.youtube.com/watch?app=desktop&v=UjkSFoLxesw
can someone please explain to me what the problems at the bottom mean, i just got the latest version of unity
then you didnt really watch them
oh i did
it helped abit, but not what i need to do
no one finishes such important concepts in less than an hr
I have a problem. when i place my (isUseable) item in the quickslots it removes it. I only want to remove it when i place it. here is the video and scripts.
https://gdl.space/imipaxohil.cpp
https://gdl.space/ahenivozoq.cs
https://gdl.space/nopiyawefu.cs
i skimmed the loops/if statements etc
because you skimmed through it
can someone please help me? im stuck for a day now ..
need some help here aswell please (ping me to grab my attention)
Unity Playground Ghost References
read this again 'when i place my (isUseable) item in the quickslots it removes it. I only want to remove it when i place it'
these seem to be attatched components, not sources for the text
maybe that's why it's null, it's literally not created
idk
it removes is from the UI when i select it but i want to remove it from thee UI when i place it in on the ground in the game world.
should i use visual studio code for coding c# in unity? im a beginner which one is the best to use?
@rich adder so i found out the thing i drag into the script is a tilemap
Visual Studio Community
thats just one part of it
but when making a new tilemap, do i just paint one tile there and drag it
or how can i do it
moving tiles aren't easy in tilemap
you would have to move the entire tilemap just for 1 platform
why do you want to use tilemap in the first place?
what else would i use?
you can just make LMR a combined object prefeb
@languid spire do you understand my problem better now?:) i really can't figure out the solution.
ok
I think I'll need to pull the playground source code myself and take a look at it. I made a thread, I'll get back to you when I'm at a computer
if you want to make a scrolling/runner game tilemap is just extra work.. Use regular gameobjects
tilemap is better for building levels with tiles
or grids
please help me up here, my AI wont move
what have you tried to debug it ?
ive checked that the function gets called
deleted and rebaked my navmesh a couple of times
which debug,.log would that be and how many times it prints
yo
am i allowed to send a youtube vid here which is pretty usefull for complete beginners
cool thanks
this is a code channel not a resources channel
in ChasePlayer, it prints out probably every frame im outside the attack radius
ok
Ach, jonge, je moet er veel meer Debug.Logs er in zetten
nederlander
hahaha, jonge ik loop godverdomme al een hele dag te kutviolen.
no, but I can read it
i'm belgian lol
try remove ChasePlayer in update and move it in start. does it work
everyone here can read dutch but can someone please help me with my problem 🥲 ...
ist wunderbar?
there is way too much of it, you will have to narrow it down and show some log output
no, but i see that WalkPoint never gets set
only thing i've done yet is make flappy bird with a tutorial, i can't srry
yeah u gotta call SearchWalkPoint first
yea
if its not moving in start you have to select the agent in playmode with navmesh selected and screenshot it
no the scene view of agent
your equipsystem calls UseItem in SelectQuickslot. Not sure if that is what you want?
it should show you debugs of navmesh, if gizmos is on
@rich adder How can i make the platforms as an object? When i drag the asset on the hierarchy nothing happens
are you sure that agent type is assigned to walk on that Navmesh layer ?
well i havent used unity AI before so if you could explain how id go about checking ?
you have to create a new empty gameobject and put a sprite renderer on it, select the sprite from what u want
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
heres the nav mesh surface
One game object for each tile?
2 child 1 parent
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
@languid spire here is my console log. how i want it to work from the inventory it works! it deletes the UI. when i do it from the quickslot it deletes it when i seleect it.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok
one note is: AddToQuickSlot should check that the thing you are putting in quickslot isn’t already there
show me gizmos for the agent on enemy i cant see it from before was too far
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;
}
}
}
}
yes
wtf is this? global::System.Boolean v = patrolDestination
== 1;
@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
that looks so complicated yet it is beginner 😭
some error came up when i wrote the script without that, so i included that and it was fixed
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
man, patrolDestination = 1;
it seems a bit out of place
yh?
@sonic remnant Example
#region Modify quickslots
AddToQuickSlot
RemoveFromQuickslot
FindNextOpenQuickslot
#endregion
#region Selecting Quickslot
SelectQuickslot
DeselectQuickslot
#endregion
…
etc
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)
why did you put them like that
i will structue it. can you help me when im done? i really want to solve this.
i just created new objects, and assigned the assets to it
i’m trying, but it’s a big system lol
didnt place them
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
*Large Code
@languid spire works now thank you so much man
I think this would have been simpler if you had split your EquipSystem and a Quickslot class
@median escarp make sure you're not coding without a configured IDE #💻┃code-beginner message
great, next time think about the error don't just 'do stuff so it goes away'
will do thank you so much guys
hello, so i followed the code in the following video. However the character controller doesn't want to jump. Any idea why?
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...
if its anything like earlier you probably mised a step
again
"followed the code" is quite common here and never turns out it is
@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?
@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
wdym inherit props ? I don't see how lining them up should be anymore complex than putting them each 1 unit away from eachother..Assuming you actually have the correct PPU set for sprites
i mean they are child classes of the middle one, when i change the sorting layer arent they all supposed to change?
@buoyant knot thanks for the tip, i will structure it and hope i will solve it ❤️
i know i’m not directly solving your problem, but I think these are handy tools as you grow out
no,they only inherit transforms
a lot of my older code doesn’t have these features, which makes it harder to read now.
ok
yep
understandable. @buoyant knot do you think when i structure it you can solve it for me?
and now i can link this game object parent to the script right?
make it a prefab before you do anything with spawning
i don't feel like it's a proper learning way
not sure lol
if someone solves it for you
and spawn one from folder not the ones from scene @raven kindle
yes
okay @rare basin but maybe when i understand the problem why its not working then i learn from it. right?
understand the problem != someone solve the problem for you
Should this be an else if?
if(velocity.y > -20)
{
velocity. y += (gravity * 10) * Time.deltaTime;
}
You have it running IMMEDIATELY after the jump, and doing the jump will obviously make the y velocity greater than -20
wdym make it show ? you just spawn it
watch some basic unity tutorials
it's hard to point you in proper direction without basic knowledge
ty
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..
@sonic remnant right, one more tool that is very useful is assertions. write Debug.Assert(somethingThatShouldBeTrue, “Error message if it isn’t.”)
actually here this ones good too
https://docs.unity3d.com/Manual/InstantiatingPrefabs.html
like this ?
ty
right
that's strange. According to video. It's not else if...
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
did you Debug.Log(isGrounded) ?
whoops wrong image
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!”);
Ah it's a +=
Sorry. Still waking up haha
no worries.
you should use a large number of Debug.Assert statements throughout your code to detect fuckups as early as possible
if you are operating on the UI it should be anchoredPosition
Its not in canvas UI, its world positions
Anchor is just a name I used to say 'be relative to here'
how to do that?
That woud likely be the result of an infinite loop
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);
}```
fuck
you're mixing two different ppl /issues lol
he asked a separate question in a void about assertions
yea true, think they thought you were replying to theirs
probably lol
no not yet
i don't even know how
nice
anyway, assertions like this will help you quickly identify bad code way earlier. Assertions are worth their weight in gold
put Debug.Log inside Update
yeah its gonna keep increasing until you run out of memory and crash
yup
Out of Memory exception ☠️
i couldnt fix it
i did spend a while trying
when i click restart as standard user nothing happened
are you running custom win 10/11 ?
maybe
yeah that would be custom , like Tiny7 etc
part of the "optimization" was probably turning off UAC altogether and/or elevated admin user
https://pastebin.com/mbSvehsv
Do you know why this is going on infinitely?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
its not the update function
I think pastebin is blocked in my country i can only open it with VPN
dang, see if you can move.
what is "this"?
I see no Debugging in your code so how do you know?
endlessly calling SpawnNextPlatforms
your if condition probably never goes false
i need to make it so it updates after the player moves over one?
about this ? any ideas ?
how do i load a specific scene?
pass name or index to SceneManager.Load
You have to porbably udatte the spawn threshold correctly
so like this
SceneManager.LoadScene(SinglePlayer);
is SInglePlayer a string or int ?
forgot it needed the "
this would still be valid and ideally smarter if you did make it into a variable
and not needing ""
all it is is the main menu where you choose single or multiplayer
private const string MyCoolScene = "SinglePlayer";
SceneManager.LoadScene(MyCoolScene);
wdym which one do you need, you named it player
oke
i still need help with AI, i was just adding scene restarting in the meanwhile
@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
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
nvm
they're moving
idk why
Why is this Object reference not being set?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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);
}
}
}
}
use site link, we cant read line like this.
*Large Code
hit save and send the link
this link isnt working
nvm its the slash at end
grid is Null apparently
you'd have to show the Grid gameobject inspector
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
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?
lookup how OnCollisionEnter works, whats the confusion ?
I just don't want to use the exit version and stop it that's all
huh? wdym the exit version
nothing forcing you to use that one lol
OnCollisionExit
ok so dont use it
Hi, My visual studio isnt working, apparently its something to do with the "miscellaneous files" at the top left. Can anybody help?
follow all these steps
!vs
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)
thank you
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
worked perfectly, thanks!
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?
ahh that's a good idea let me try that
you should use a coroutine
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;
}
Oh goodness
Thanks haha :)
I forget... in PONG after the play scores do the paddles reset too?
Pretty sure they do yeah
Back and do you mean by SerializeField?
no, the inspector for Grid gameboject
Oop my bad I thought they did
The grid object has the code for it but shows nothing else unless you mean by code
can you screenshot the object
Hi, can you show the code where you update the positions of the paddles and the ball? Might be an issue with fluctuating frame rates?
I know but don't at the same time
We solved it, but thank you!
well what do you think,
its ok to guess
How did you setup/paint these tiles btw ?
Is calling the Grid the code and calling to the type which is the object
Little circles
close but kinda otherway around
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
There's a Grid componet?
Oh, that makes a lot more sense
your code uses functions from it
did you copy and paste this without understanding it ? lol
No, I followed a video in my class and it told us about this stuff but never told me about that
From Mastercoding
I don't think I did and it's good as they are fixing stuff constantly but they still need feedback
well the script is looking for the component and using some methods from it. I'd assume it is needed somewhere
That is fair, but thank you very much for the help.
How do I wire this timer to show in the UI/UX?
Like I have a TMP text object and I want it to show the countdown
dont make a timer inside a ball tbh
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
the "other" is somehow wrong in vs and is marked red whenever I write it
show
so what is other
It needs a reference
Like what for example?
do you know what a method parameter is?
Not really been in that area much
side effect of blindly copying code
read the Trigger method is giving you a Collider2D
So it needs the collider as reference?
Then what are you trying to check the tag of
The player. If it runs past the start sign through the collider it should play an animation
And when the animation finishes should be able to do it again
Okay so what is other then?
Nothing right now
So then why are you checking the tag of nothing