#š»ācode-beginner
1 messages Ā· Page 82 of 1
yeah, foreach will mess you up if you do edit the ienumerable
like this? myDic.Add("level", (int) reader.GetValue(reader.GetOrdinal("level")));
@rich adder no I didn't mean that at all. I meant something close that I could look at and adapt to what I want, but everything I've seen is about creating a 'linear' level etc.
the way of your generation should be quite similar to this
https://www.youtube.com/watch?v=BIa_gqc93ok
Hate the classic box dungeons? I re-imagined the classic Minecraft Dungeons using jigsaw blocks to add custom structures to Minecraft with no mods using datapacks! And this video is a complete guide from the basic concepts to the technical details of how to make custom structures to Minecraft for yourself!
Data Pack Template - https://drive.go...
i figured it out thanks now my game has somewhat functional multiplayer
sure
or the alternative I mentioned
so im trying to spawn prefabs in but its not showing but it is spawning?
is one better than the other? or can I just choose?
2D ? is it infont of cam?
e.g. myDic.Add("level", reader.GetInt32("level"));
take a look on the camera position, scale of prefabs
check Z position of camera
it must be smaller than the scene objects
-10
ok and how about spawned objects
1370.9
view dsitance?
That's pretty far away for 2d
when i drag the prefab in i can see them but when they spawn in they dont show up
look at your cameras view distance. it defaults to 1000
yes but what is their X and Y position
Compare the positions
ah my bad, missed that
maybe the camera is perspective, it is extremely small
yeah maybe
But it does still have a clipping plane, right?
oh yeah ur right
shite could be clipped
thanks ā¤ļø did quite a bit of searching for this but couldn't find it š
works perfectly
yeah wheels are weird man yu have to set them up in a certain axis
ok so now its not even showing up in the scene view
can you like show the setup or something, I'm personally not trying to play 20 question lol
What's your cameras far clipping plane?
is there a vc i can join to show?
What is the position of the object when you can see it, and what is the position of the object when you cannot
Show the camera settings
That's a prefab show the object in the scene
whats that mean
Tried like 5 times to update VS22 from 17.8.0 to 17.8.2 but keep getting this. Anyone experiencing the same?
VS installer is shite
whats this mean
had to reboot my whole system one time cause it kept telling me couldn't install VSredC++
and another VS installer was in use
total shite show from Microsoft @modest barn
Show the object that actually exists not the prefab
Change that 1000 to 2000 or something
No, fix the position of the object
i did now my player wont show uo lol
it should not be that far from the camera
show us where the Pipe is spawning when yu spawn it
that aint the pipe you spawned. try again
the pipe
thats where the pipes spawn
show a pipe
also You are configure things with Center pivot mode. guaranteed your Pivot is wayyyy further than you thought
hate that Unity defaults it to that..
Yeah the Z axis is massive
Yeah I mean it still works for Unity but trying to make a normal project will probably become a real pain. It's a school computer and I only use it there so I don't really care š
Why is it that far away
flappy bird?
yeah its a small update but still..annoying af it does that
Don't spawn it at that position
Thankyou ā¤ļø
You define the position you spawn it at
Your spawner is at z5, so that should be at z5 too imo
I still think the pivot is probably not where thy think it is
Unity is putting it on Center which looks ok
but when yu spawn it it uses the Pivot point
how do i change the pivot
which is probably not where Center is showing
first switch pivot from Center to Pivot
so we can see
ok i clicked pivot
drag pipe prefab in and press F
ok i did'
ss
oh well its that one is good then
it still not showing up and idk why lol
so lets see the code that spawns it @queen adder
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeSpawnScript : MonoBehaviour
{
public GameObject pipe;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Instantiate(pipe, transform.position, transform.rotation);
}
}
also when you spawn it with code you could also Press F on it and see where it went
!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.
i followed a tut
shouldnt this be like crashing at some point
This is putting the pipes at the z position of the spawner. what's the z location of the spawner?
first game lol
also yes you're spawning a new pipe every single frame
which is defintiely not what the tutorial did lol
yea i havent fixed it yet
This is spawning a pipe every frame so the reason you don't see anything it's probably because you're getting like, minutes per frame
i wasent done yet i just needed to see rthem spawning
So fix that
ok
so im trying to make a double jump for my character how would i check for when they land to reset the jump counter
Use your grounded check
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeSpawnScript : MonoBehaviour
{
public GameObject pipe;
public float spawnRate = 2;
private float timer = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer =+ Time.deltaTime;
}
else
{
Instantiate(pipe, transform.position, transform.rotation);
timer = 0;
}
Instantiate(pipe, transform.position, transform.rotation);
}
}
fixed
Why do you still have a spawn every frame
Nobody can help without knowing details about what and how you're doing what you're doing currently
the delta time fixes that
oh wait
dont mind that
i accidently left it lool
ok now its fixed
well i have a OnLandEvent that i made but that triggers when i leave the ground aswell so doesnt work well
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeSpawnScript : MonoBehaviour
{
public GameObject pipe;
public float spawnRate = 2;
private float timer = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer =+ Time.deltaTime;
}
else
{
Instantiate(pipe, transform.position, transform.rotation);
timer = 0;
}
}
}
great now #š»ācode-beginner message
Sounds broken. Use your grounded check
wym?
problem is the grounded check is in another script
the z is 5
So now run the game, and send a screenshot of the spawned pipes
did yu follow the guide provided to you
#š»ācode-beginner message
its not that difficult
its not even spawningthem at all
You should focus on the basics of Unity to master inter-script communication
wdym isn't right? do you see you have to configure the vehicle with axis of wheels on Z
thats how wheels work
yea its not doing anything
Hi i have this code here it zooms in but not out again
if (Input.GetAxis ("Mouse ScrollWheel") > 0)
{
if (cam.fieldOfView <= defaultFov && cam.fieldOfView > maxZoom)
{
cam.fieldOfView--;
crossHair.SetActive(false);
}
}
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
if (cam.fieldOfView > defaultFov)
{
cam.fieldOfView++;
crossHair.SetActive(false);
}
}
Use Debug.Log, start investigating which bts of code are running and not running and why
ok so they are spawning and i can hit them but i still cant see them @rich adder
so i used the grounded check but it still doesnt work the first jump gets deleted
i can see them in scene view but not game view
select one of the spawned pipes at runtime and press F
screenshot it
True i will do that
well where's your camera?
WHY is the clipping plane like that
someone said to change it to that
no you put it back how it was
no way did anyone say that
what do i change it to
the default, like 0.3 or whatever
Thanks it helped for me to debug it because i found out my error it was at if (cam.fieldOfView > defaultFov) where it had to be if (cam.fieldOfView < defaultFov)
whats the defalt
yes 0.3 - 1000
yep that's what debugging is for
- No they didn't, they said 2000 not 20
- Don't change it anyway you shouldn't have done that in the first place
no someone private messaged me
This is why you don't take problems into DMs because then there's no one to double check when you get stupid advice
We have a system of checks and balances here, we are all dying to correct each other on bad advice so if it's a public answer someone will call it out
what do you think next step is ?
how can i make my gameobject the be on top of the ui when hovering with the mouse over,
testing
use screenspace camera
same thign they are in scene view and i can hit them but cant see
What are the z positions of pipe top and pipe bottom
What do You mean?thats the camera im using
if you're using a screenspace camera then it should be as simple as changing the Sorting Order
put the gameobjects one higher
if they're not sprites then it gets more tricky
youd have to change the Plane distance and make sure it correct
They are empty game objects that have sprites and text(a card)i've tryed sorting layer and it didnt work for me,also,the gameobjects are somehow seetru in scene but not in game
(Quick?) question: I'm using Resources.Load<X>("Something") to load a Prefab. At some later stage i want to check wheter a given GameObject is instantiated from the same Prefab (or is of the same type or whatever way is the best). Any ideas?
they might be behind the camera, for the second part
this isn't really code related, move convo to #š»āunity-talk . Show the setup of your canvas and your gameobject sprite /
Oke,thank you
store it in a variable? not sure what youre asking exactly
can you elaborate the use case
i set my bulletpf with the z axis of 90 but when instantiate it reset to 0?
you're assigning this object's rotation to the bullet when you instantiate it
i thought it would adding to the object rotation
no, it assigns exactly the rotation you pass
i see
plenty of tutorials for that if you google it
please see #854851968446365696 for what to include when asking for help
go from vague to only slightly less vague, nice
guess they don't want help š¤·āāļø
yeah not anymore
Okay, so would anyone be willing to take me step by step (not code, just 'steps') in getting this map generator idea working please?
well we can't help you without useful information
how would i make just a check if they collide into anything?
huh?
Especially in a code channel, we'd have to see the code @tiny vault
we're not mind readers we don't know your exact setup
i have an idea i will give you the code if it doesnt work
i thought about it and reaslised for double jumps it would be better for just if they collide with anything because if you land on a enemy or smth then you still cant jump
okay it doesnt
well have you googled how to do a ground check? because if you had, you'd find plenty of tutorials for how to detect ground using physics queries like raycasts
would it matter if i just send a part of the code right here
!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.
Yeah, thanks. Not sure how to formulate. I'm filling a Dictionary<GameObject, int> using Resources.Load to get the GameObjects and incrementing the int for every Resource. Later I'll get a (random) GameObject and want to get the associated int from the Dictionary.
Lets say I have Prefab "Red" and Prefab "Green" => Dictonary([Red, 1], [Green, 2].
Now i get GameObject go which might have been instantiated from the Prefabs "Red" or "Green". I can't throw go at the Dictionary, because that specific GameObject won't be in the Dictionary.
send link
i donāt understand how collision gets factored into this
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
mate the whole script
this alone isn't helpful
anyway if youre using one of the OnCollision/OnTrigger methods @tiny vault
https://unity.huh.how/programming/physics-messages
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i made a simple camera lerp script
[SerializeField] GameObject player;
[SerializeField] Vector3 cameraOffset;
[SerializeField] float cameraSpeed;
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
Vector3 NewPosition = new Vector3(player.transform.position.x + cameraOffset.x,
cameraOffset.y,
player.transform.position.z + cameraOffset.z);
transform.position = Vector3.Lerp(transform.position, NewPosition, Time.deltaTime * cameraSpeed);
}
this smoothly follows the player in editor but when i make a build it sometimes feel jitery any idea why its happening
so with this it doesnt work on the object that has the tag "Special" but it works on the object that has "Money"
if (myDict.ContainsKey(redObject) {
myDict[redObject] = 1;
} else myDict[redObject]++;
So I've created a simple breakout game, any thoughts on what to build next for learning?
does this object have a rigidbody on it or the other one that works?
both of them only have box colliders with "is trigger" on
depends what you want to learn
i expect this to be a bit jittery
but not feeling jittery at all in editor
Sorry, my problem is not filling the Dictionary, its getting the corrent type/component or whatever of any given GameObject that would fit the Dictionarys Key, if you know what i mean?
you made the game play stuff,
are you interesting in doing the non-gameplay stuff thats annoying but also important ?
like a Menu and a full game loop / high score saving, with all that other junk that goes with simple game states @dense root
probably just not as obvious with the smaller screen
i would give camera a kinematic rigidbody, and tell it to lerp toward player position every fixed update frame
nah not actually
hey, does anyone how could i choose net4? is needed that one for firebase
i only need to make this object work in the next 40 minutes
you need at least 1 rigidbody between the two when u want trigger to work
.net framework is .net framework 4.x
the character has the rigidbody
oh, thanks
the objects dont
lemme me try this
no i do not know
and which one is the one that doesnt work
object with the "Special" tag
just remember to use rigidbody.MovePosition
that should smooth everything out
The basic idea I have is that I have a 'starter/spawn' room (blue in the image) which has four doors, one on each 'face' which I'd like to iterate through and spawn new rooms onto each 'door' (this happens every time there's a new door that has a free spot next to it. I had a method that sort of worked, but it's wrong, so looking for another solution but I'm at a bit of a loss on how else to do it. All I need is the steps, I can work out the code myself. š
so what is supposed to happen that isn't?
the object doesnt get destroyed and doesnt give any points
google wave function collapse algorithm
thre isn't a cookie cutter answer to this. There are a lot of devblogs you have to swift through, big part of why they're devlogs and not tutorials.. each has their own methodology
you mean you want a dictionary where you input a string, and it spits out the prefab gameobj associated with it?
i just donāt understand your goal here
Simplyfied rephrase:
GameObject prefab1 = Resources.Load<GameObject>("Test1");
GameObject prefab2 = Resources.Load<GameObject>"Test2");
GameObject instance = Instantiate(prefab1);
What comparison can i do to get a "true" out of prefab1 and instance, but a "false" out of prefab2 and instance?
you mean you want to know you have a running instance of prefab1?
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground" || collision.gameObject.tag == "Enemy")
{
grounded = true;
Debug.Log("Grounded");
}
}
would this check if you collide with the ground or the enemy??
if you're going to ask for advice in here, why not actually take the advice instead of ignoring it and implementing your own (worse) thing?
Give all the gameobjects a component to communicate with an entity-ledger system. This component can hold different types of info, and in this case holds a ref to the relevant prefab.
When this component has its Start(), it tells an EntityLedger singleton to log a new instance (itself) under prefab1. When it is destroyed, it tells entity ledger to delist itself.
you said look up a tutorial i did
they advised something like raycast, this isn't even close to raycast lol
i also specifically mentioned using physics queries which would be so much better than relying on collision messages.
then you can query entity ledger, to see how many of each instance you have, or even to control everything associated with a given prefab
alright i will watch a tutorial on those now
you're also not even checking the tags correctly so whatever tutorial you followed is garbage
entity ledger can maintain a Dictionary<GameObject, HashSet<EntityDataHolder>>,
where the key is the prefab, and EntityDataHolder is whatever component weāre putting on the gameobject to keep tabs on it.
Put a script on the room that has a list of doors on it. Give the doors a script that lets you know if a door has something on the other side of it. When you spawn a room, call a function on it that checks each door, if it's empty, spawn a room there (which will itself call this "door checking" function when it is spawned). If a room spawns and all of its doors are occupied, you can just return from the function without spawning anything else, which serves as your escape condition from the recursion
i do this sort of pattern a lot, and itās very helpful to just keep tabs on things
That sounds awfully complicated for what I'm trying to archieve, but maybe there isnt a way around it in Unity. In general OOP i would do a typeof check and thought there should be an easyer way here
prefabs are all of type gameobject
meaning you need to give the gameobejct a way to identify itself
Thanks guys, looking at Wave Function Collaps atm. but will have a look at what you suggested @polar acorn š
Tags can work, but that can break any other uses for tags that you have
like, I do a similar system for reference frames, entity ledger, and physics movers. All of these have singletons that need to keep track of ALL active instances
so I usually have the one Singleton class that holds a collection of all the individual instances. And the individual instances have a monobehaviour to communicate to it. To tell the singleton āinclude me now.ā and āiām gone nowā
otherwise, you need to do fancier things to make sure you keep perfect track of things that enter/leave your records
which is a giant pain in the ass
itās better to have a monobehaviour just automatically take care of registering/deregistering itself from a common place.
if you donāt care if it has been destroyed, and just want to count ātotal active ever made, including destroyedā, then you donāt need the extra monobehaviour
itās like a hotel, and making sure each guest signs in and checks out, so that the hotelās ledger can tell you exactly who is in the hotel at any time
if you donāt ask for checkout, youāre more like a movie theater, who just wants to count total tickets sold ever
understand?
@buoyant knot Thanks for all the ideas! I think using the tags should work. They are already tagged differently anyway.
Wave Function Collapse sounds like it would make a great band name
So I'm trying to make a Galaga style projectile spawner, how do I go about spawing the SpriteRenderer and any other components necessary?
// Projectile spawner
if (Input.GetButtonDown("Fire1"))
{
// Instantiate projectile at the position and rotation
Rigidbody clone;
clone = Instantiate(projectile, transform.position, transform.rotation);
// Give the cloned object an initial velocity along the current object's z-axis
clone.velocity = transform.TransformDirection(Vector3.forward * 10);
}
Put them on the projectile prefab
@buoyant knot Jep, tags did the trick š I've been using tags to identify the instances already anyway, so this is acutally a straigt forward solution to that problem. If I'm running into problems with the tags in gerenal at a later time, I'll have to find another solution to identifying them. Thanks again!
sure. make sure to use a plugin to avoid using tags as plain strings
you seem confused. If the projectile prefab has those components, then what you are doing now spawns the whole prefab including all those components
you don't need to separately spawn different components
I see
there are several. I have one that just autogenerates a static class with public constants. So I can use Tags.PLAYER, instead of āPlayerā and misspelling it
Let me do some tinkering and I'll get back to you with any issues that might arise
Thats a good idea as well. I hate using strings for anything for that reason š
openupm has several different plugins
The plugin auto generates a new tag constant whenever you create a new tag via the editor?
you have to click on a menu, then it autogenerates the class
That sounds convenient enough
the biggest time cost is setting up openupm, which youāll probably want for other things anyway
Welcome to OpenUPM, your solution for open-source Unity Package Manager (UPM) packages. OpenUPM is a user-friendly service that hosts, manages, and automates the building of UPM...
itās a curated list of open source packages. and openupm lets you quickly add packages to unity, and grab any dependencies
so im following the video and mine is the exact same as his but mine is giving me a error
show code show error
private bool IsGrounded()
{
return Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.down, 0.1f, jumpableGround);
}
Severity Code Description Project File Line Suppression State
Error CS0103 The name 'boxCollider2D' does not exist in the current context Assembly-CSharp C:\Users\vinny\gravity brawl\Assets\PlayerMovementSinglePlayer.cs 116 Active
Severity Code Description Project File Line Suppression State
Error CS0103 The name 'boxCollider2D' does not exist in the current context Assembly-CSharp C:\Users\vinny\gravity brawl\Assets\PlayerMovementSinglePlayer.cs 116 Active
private BoxCollider2D boxCollider2d;
private void Start()
{
boxCollider2d = GetComponent<BoxCollider2D>();
}
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 138
Number of times it was exactly like the tutorial: 4
Number of times the code literally did not exist: 1
2022-07-19 to 2023-11-29
you spelled it wrong
yes. caps
boxCollider2D
boxCollider2d
you probably want a simpler name, like boxCol, or mainCollider
yeah probably
Got it! Thanks @wintry quarry
yeah
Pong turned into brickbreaker! For a second I thought you were giving one player a huge advantage haha
Pong turned to brickbreaker now into Galaga!
It's a lot of fun just 'morphing' the game into another game. Learning ALOT too
so with that i still have the same problem so i have a jump counter and the first jump it sets it to 0 instantly after it sets it to 1
so it never goes above 1
That's in due time š
if (Input.GetButtonDown("Jump"))
{
if (jumpcounter < 1)
{
jumpcounter++;
jump = true;
if (jumpcounter == 0 && IsGrounded())
{
animator.SetTrigger("Jump");
}
if (jumpcounter == 1)
{
animator.SetTrigger("DoubleJump");
}
}
}
this is my jump code
public void OnLanding()
{
if (IsGrounded())
{
animator.SetTrigger("Land");
jumpcounter = 0;
Debug.Log("Landed");
}
}
and thats my land code
Show IsGrounded()
private bool IsGrounded()
{
return Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, 0.1f, jumpableGround);
}
How do I go about making my prefab originate from the player position?
There's like 6 different overloads for instantiate go look em up
is there an easy way to make coroutines that just execute at a specific time within a given frame?
I find myself wanting to do things like: yield return new WaitForEndOfThisFrame() or WaitForEarlyFixedUpdate()
If this is something that you need to do you've probably got a fundamental problem with your code structure somewhere. It's nearly impossible to have that sort of fine control over the update order because it never should matter
so, for things like pausing, I want to be able to receive a pause command at any point of a frame, then basically wait for everything going on in the frame to resolve, then execute the pause
yield return null
BoxCast returns a RaycastHit.
So the bool is checking if it exists..
Not sure that should matter if you have the layermask set up right.
But you could debug that raycasthit to see what you actually are hitting
doesnāt that wait until next frame?
meaning i could have a fixedupdate frame in the middle sometimes
technically it return a bool š
pass the transform.postion
Proxy bool haha
early fixed update is a bigger deal imo, because WaitForFixedUpdate executes after collision callbacks
2Dboxcast is weird af it doesn't have out param but it puts results in array if you pass it as param
so if I try to move something in coroutine that does WaitForFixedUpdate, then there are potentially many normal Update frames where things can change before we get to the FixedUpdate that actually plans to evaluate that call
but I wanted to issue the move command on the same fixed update frame where I know it plans to go off (before physics sim)
does this all make sense for why I want that level of control?
How do I pass the transform position of the player to the prefab?
so i might just not be understading you but my problem isnt that its not hitting it its that it hits it to much
i think my pausing affects how that coroutine interacts with my physics system because pausing happens in Update loop, and stops everything.
after the first jump its still hitting the floor it says
public int BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance, RaycastHit2D[] results, [DefaultValue("Physics2D.DefaultRaycastLayers")] int layerMask = -5)
{
ContactFilter2D contactFilter = ContactFilter2D.CreateLegacyFilter(layerMask, float.NegativeInfinity, float.PositiveInfinity);
return BoxCastArray_Internal(this, origin, size, angle, direction, distance, contactFilter, results);
}``` šµāš« @summer stump the version with colliders2D[] returns an int. welp
i guess thats colliders hit amount
mostly use Cast in 2D
the same way we pass other data xD
reference it
pass it as a variable , it's a property inside the Transform player.transform.position
for simple shapes, I ran some benchmarks, and it is almost as fast as a raycast, but it has obviously a lot more accuracy to the shape
like, Physics2D.Raycast and BoxCollider2D.Cast are similar speed
mindblowing that They have an overlap for 3D in phyx for Mesh Collider but not in unity
spamming a fan of raycasts is a lot more expensive and innaccurate than .Cast for a shape
PxScene::overlap() query searches a region enclosed by a specified shape for any overlapping objects in the scene. The region is specified as a transformed box, sphere, capsule or convex geometry.
š¢
Physics.OverlapConvex
ouch
would be neat
they are losing a ton of market share now to Godot, so weāll see how that changes the stream of new toys
its weird cause doesn't OnTriggerEnter use that?
You can technically make a convex shape and mark it as isTrigger
and use OnTriggerEnter and it works
unity does a lot of black box things, where they get to use a tool, but we donāt
one really annoying part is how classes get sealed. so you canāt easily make wrappers to add fields etc
closed source nonesense this would've been added ages ago, its literally in the script somewhere surely we can turn it into a Physics. class method
thatās why I think Godot will flourish, once it gets its shit together
it is obnoxious to code and not be able to change basic things
they have lot of YEARS of R&D to catchup to
they are friendly with other things that are nice (newer .net) but still their game engine tech is very primitive
anyone got some ideas of how to fix this issue
you know CustomCollider2D? no reason that should be a sealed class. It is literally perfectly designed to allow you to make your own parametrized collider classes
instead, I need to do awkward dictionary bullshit to couple a wrapper class to it
which leads to a lot of issues in Awake and Start
is it possible to make a thing move towards shadows
like if its in light it will go towards dark areas
not an easy task
ofc anything is possible
you'd have to determine some way , what shadow area would be
light probes maybe
wdym still hitting the floor ?
so basically the instant you make the first jump the counter gets reset
ok what about the script can you show inspector for this script, screenshot
how do you call OnLanding
OnLanding is called in the update
public void OnLanding()
{
if (IsGrounded())
{
animator.SetTrigger("Land");
jumpcounter = 0;
}
}
but it has the if to make sure it only happens when your touching the ground
Debug.Log(IsGrounded());
above if()
jump and try again
is there a way to delay part of the function by 10 seconds or 20 seconds without using coroutine and invoke.
the part i want to delay is within multiple if statements so if i use script method it doesn't work.
time += Time.deltaTime. it doesn't work either
why wouldn't it work ? whats the use case, they can also be coroutine functions and they can each be yielded
no difference only it spams my console with true and false
why would a debug.log make any differences?
it doesnt change any functionality
idk
you have to observe the log when you jump
i don't know why it's not working
i want the enemy character to move in a direction after 10 seconds
pause the game if you must as soon as you jump
whats "not working"
idk what that means in this context
very least share the code you currently have
when i use
timer += Time.deltaTime
then it should increase the timer value by 1 every second but instead it increases its value by 0.01 something
is there a way to do that via code so it pauses the instant i press space
Debug.Break()
in jump code
so the problem seems to be it adds to your jump counter before you even have a chance to move
because it ends with true
show current code
wdym
you're grounded midair ?
no but i increase jumpcounter the instant i hit space
yeah thats what the code you wrote is doing, what does that have to do with it going to 0
you don't
well if your still grounded technically it auto sets it to 0
You don't. Those are two entirely different things
transform contains more than just a vector3
public void OnLanding()
{
Debug.Log(IsGrounded());
if (IsGrounded())
{
animator.SetTrigger("Land");
jumpcounter = 0;
}
}
this is called via the Update()
transform.position
thanks
š«
But keep in mind that is not converting it simply using the position property of the transform
Hmm this bit of code still puts the projectile dead center in the screen
// Projectile spawner
if (Input.GetButtonDown("Fire1"))
{
// Instantiate projectile at the position and rotation
Instantiate(m_projectile, m_paddle.transform.position, Quaternion.identity);
}
thats what Im saying.. your Grounded is being set before you even lift off the ground
which makes sense since you're only doing animation
if (jumpcounter == 0 && IsGrounded())
{
animator.SetTrigger("Jump");
}
if (jumpcounter == 1)
{
animator.SetTrigger("DoubleJump");
}```
nothing here is actually moving the transorm maybe the animation? even so then its too slow for update
Then m_paddle.transform.position is likely dead center of the screen
!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.
š
pasted in a rush myb š
It's not
Try logging the value of it, and compare it to where it ends up in the scene
Oookay, more adventures in Map Generation.
Playing around with Wave Function Collapse, and I understand a good chunk of it (followed a simple tutorial). Now the issue is that I need to 'convert it' from using X,Y in 2D space to using X,Z in 3d Space, and I'm struggling to understand what I need to change etc.
This is the entire thing (3 seperate scripts, Tile, Cell and WaveFunction.
The only place that I can see with my novice eyes that would change from 2d to 3d space is the Instantiate command, so I changed that but then I get an error. Would anyone more knowledgable be able to poke the right places please? š
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.
so it moves me up i just forget where i have it do that i made these scripts a while ago they just today stopped working
surely Jump is being called somewhere then
void FixedUpdate()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
found it
im gonna be honest i have absolutly no clue all i know is if i comment it out you cant jump
Can someone help me with my little test game im making?
oh yeah
you have to post an actual problem..
https://pastebin.com/kZQ5fEPp thats the Move
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.
i forgot i for some weird reason split my character controller stuff into 2 different things
NullReferenceException: Object reference not set to an instance of an object
What does this error refer to in this code?
// Projectile spawner
if (Input.GetButtonDown("Fire1"))
{
// Instantiate projectile at the position and rotation
Instantiate(m_projectile, m_paddle.transform.position, Quaternion.identity);
Debug.Log(m_paddle.transform.position);
}
What am I not setting to an instance here?
i also put way to many comments in that one
first thing to look at is the line number
wihch line is it?
What line has the error
Instantiate(m_projectile, m_paddle.transform.position, Quaternion.identity);
m_paddle is null
The only thing here that could cause this is m_paddle being null
not the greatest but should move it fine. maybe make that jump be Impulse force instead of gradual addforce in update?
you can't have it there with impulse tho cause it will keep calling it (unless the grounded is working ok in there ig)
Well here is my script first of all https://paste.ofcode.org/VSjU6M5YZDTp9s3i8b9vLz
I have a player and this player can pick up blocks and place them on the ground again. This mechanic works perfectly, but i also have some block plates where when a block is touching it and its being held by a player it will be dropped on the position of the block plate. I can also pick up the block from the block plate. The problem is me being able to place more than 1 block one 1 plate, and when i have more than 1 plates in the scene it also gets weird. Can someone help me? i use prefabs for the blocks and for the plates fyi.
is possible you can make video so can easily tell whats the setup too
honestly i think today im gonna spend the day remaking my whole player movement now that i know more that way i can make it way better
yeah that sounds smarter
because it is extremly scuffed rn
Hi guys ! simple question. How do I reset the position of my camera, i'm lost in my scene
Select an object from the hierarchy and press F
also you already a had groundcheck there so adding another was redundant and prob harmful
since one is inside Update and the other FixedUpdate
idk that might be ones more accurate then the other, but I think they both are on physics timeloop anyway actually..
private void FixedUpdate()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, 1000, layerMask) && isPlacingObject)
{
if (pendingObjectContoller.inFloor)
{
addedY += 0.1f;
}
else if (pendingObjectContoller.aboveFloor)
{
addedY -= 0.1f;
Debug.Log(addedY);
}
pos = new Vector3(hit.point.x, hit.point.y + addedY, hit.point.z);
}
}
Hey there having an issue with this part of the code for some reason going up works, however I can't seem to get the going down to work the bools do change too so thats wierd.```
!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, I got what you meant. Debugging what you hit is the first step of finding why it's hitting too much
addedY is printing ?
@pure crown Show how pendingObjectController.aboveFloor is set
using System.Collections.Generic;
using UnityEngine;
public class ObjectContoller : MonoBehaviour
{
RaycastHit hit;
float distanceToGround = 100f;
public LayerMask groundLayer;
[HideInInspector] public bool inFloor;
[HideInInspector] public bool aboveFloor;
private float distanceFromFloor;
// Update is called once per frame
void Update()
{
if (Physics.Raycast(transform.position, -Vector3.up, out hit, distanceToGround))
{
transform.rotation = hit.collider.gameObject.transform.rotation;
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.layer == groundLayer)
{
inFloor = true;
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.layer == groundLayer)
{
inFloor = false;
}
}
private void OnTriggerEnter(Collider other)
{
aboveFloor = false;
//Debug.Log(aboveFloor);
}
private void OnTriggerExit(Collider other)
{
aboveFloor = true;
// Debug.Log(aboveFloor);
}
}
I tried doing it with raycsts but I been running into issues so i thought maybe a trigger can solve it quickly
it does print however
I have a youtube link is that ok?
You able to take dm's?
@rich adder
negative
i think i say in the video
both printing btw
gotcha
first I would clean your script a bit, also those white blocks should be their own script
name.Equals("BlockPlace") using name is a big no
there is only 1 player so it is acceptable (still bad practice to use strings/names)
but for multiple cubes not ideal
You make a script a nd make them a component
so you only check component
for the player or the blockplates?
all of them
so i dont check if the object im touching has the name Player, but i check if the gameObject has a component that is the movement script or something else?
does someone knows why do i get this both logs when i try to use google firebase I'm just doing it for android and it say something about IOS
collision.gameObject.TryGetComponent(out Grabbable grabable )){
heldObject = grabable
for example
what does the (out Grabbable grabable do?
it looks for a component Grabbable , just a script lest say you make.. if it find it then it outputs that into a variable called grabbable
same as doing GetComponent with null check
so if the script has been found it outputs the grabable as true
the code inside brackets is the true part that gets run
grabbable is just the particular component you found yes from that object
this way your Whitesquares can have their own slot for Grabbable lets say
and you can check if that slot is alreaady occupied, you can't place one again
so should i now make a script for the white squares and make it so if it collides with a block it grabs it, and if its already holding one it wont.
yup exactly
or you can manually placre it from your hand
but i still want to pick them back up from the white squares
does transform.Translate work weird in 2D core?
is that still possible?
and you can check the closest white squre
yes ofc
"work weird" ?
im gonna try
No
OK so I am trying to make a Pacman clone and while I will do things differently, I decided to make the pacman controls first but for some reason (1,0) and (-1,0) make it go left while (0,1) and (0,-1) vectors make it go right
Show !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.
dont copy just an example
public class WhiteSquare : MonoBehaviour
{
public RedSquare CurrentHeldRedSquare;
public void SetSquare(RedSquare sq)
{
if (CurrentHeldRedSquare != null) return;
CurrentHeldRedSquare = sq;
}
public void OnTriggerEnter2D(Collider2D other)
{
if(other.TryGetComponent(out RedSquare red))
{
SetSquare(red);
}
}
}
public class RedSquare : MonoBehaviour{}```
hi everyone, any idea why i might not be hearing my audio with this code? using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinCol : MonoBehaviour
{
[SerializeField]
public GameManager GameManager;
private AudioSource audioSource;
public AudioClip collectSound;
void Start()
{
audioSource = GetComponent<AudioSource>();
}
private void OnCollisionEnter(Collision collision)
{
if (GameManager != null)
{
GameManager.totalCoinsCollected++;
Debug.Log("Coin collected! Total coins: " + GameManager.totalCoinsCollected);
if (audioSource != null && collectSound != null)
{
audioSource.PlayOneShot(collectSound);
}
Destroy(gameObject);
}
else
{
Debug.LogError("GameManager is not assigned in CoinCol script.");
}
}
}
transform.Translate(moveDirection * moveSpeed * Time.deltaTime);
This is the transform.Translate part
moveSpeed is a float
moveDirection is vector2 (and I tried vector3 as well)
the red squares have a grabScript so does this work?
you have to switch the logic then a bit
i just want a coin sfx to sound when i collect a coin lol
just put a method on the white square to send/check itself from red square then @modest stag
I am printing moveDirection * moveSpeed * Time.deltaTime part as well and it seems to be working as I intended
public class WhiteSquare : MonoBehaviour
{
private RedSquare currentHeldRedSquare;
public void TrySetHeld(RedSquare sq)
{
if (currentHeldRedSquare!= null) return;
currentHeldRedSquare= sq;
}
}
public class RedSquare : MonoBehaviour
{
public void OnTriggerEnter2D(Collider2D other)
{
if (other.TryGetComponent(out WhiteSquare white))
{
white.TrySetHeld(this);
}
}
}
ah sorry
Hmm, that is odd for sure. Could you paste the whole script in a paste site?
From what you showed alone, it shouldn't work like that
When you do the if (other.TryGetComponent(out WhiteSquare white)) what does the 'white' mean
It is the name of the variable you are declaring
it doesnt mean anything, is just a name for the variable of that component found
"If you find this component store it as 'white' "
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.TryGetComponent(out WhiteSquare white))
{
white.TrySetHeld(this);
}
!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.
What is the WhiteSquare refering to ?
something the gameObject your colliding with has?
A component
So a script for example?
Even the AI says that it should allow movement in 4 directions (also apparently the AI explaining the code is a thing now. Didn't know that. Woah)
as we all know, AI is never wrong
ty
is it bad to use a character controller that has custom physics so no rigidbody and no colldier
script = components
yep
ok
components are Unity specific
theyre only components when they are attached to a gameobject?
normally classes are objects
when its Monobehavior
so yea pretty much
Vector3.right or Vector2.right are global directions right? not local? The Unity Documentation says that they are global
world space*
Yes they are. The are (1,0,0) and (1,0) respectively. If you use transform.right it is (1,0) locally, translated to some world space vector depending on the transforms rotation.
I'm opening unity to check out your code you sent earlier. Easier to do hands on sometimes.
thanks
Vector3.Right is just a constant, just like how Color.Red is a constant
@rich adder how do i make it so when they touch the red square actually goes to the position?
Predefined values
under currentHeldResSquare
currentHeldResSquare.transform.localPosition = Vector3.zero;```
or you dont even need to parent, up to u
hey so i have noticed a bunch of really advanced character controlelrs and stuff have speed called m_Speed why is that
@rich adder now when i pick up a block and let it collide with a white square nothing happens, but when i place it again it goes back to localPosition, how do i make it so when i let it touch the white square it has the same position as the white square
Just naming convention for variables
ok
m_ for member variable
lets make a thread, and send both script you did with pastelink site
If I completely remove HandleRotation it works perfectly.
Then I remembered that transform.Translate has a second (default/optional) parameter that says it is local space
so change that second parameter
transform.Translate(moveDirection * moveSpeed * Time.deltaTime, Space.World);
https://docs.unity3d.com/ScriptReference/Transform.Translate.html
If you really think about it philosophically, they aren't inherently global or local. They don't take on such a meaning until they are used somehow. For example if you do transform.forward = Vector3.forward; it is "global" but if you use it like transform.rotation = someObject.TransformDirection(Vector3.forward) then it's "local" to someObject.
Btw, the rotation seems messed up a bit. I redid the code in my testing, and this is what I came up with:
https://pastecode.io/s/mhfte3hx
Oh, and I didn't do it, but you may want to reverse HandleInput and HandleMovement so it responds on the same frame, but not a big deal
what's the input method used to capture the movement of the mouse?
depends on which input system you are using
I'm facing a challenging issue in Unity where my constructable objects are incorrectly allowed to be placed through 'Tree' tagged objects, despite having collision detection logic in place. Here's a brief overview:
I have a script attached to my constructable objects to control their placement in the game world.
The script includes an OnTriggerEnter method intended to prevent these objects from being placed through other objects, particularly those tagged as "Tree" or "pickable".
Despite the logic, the constructable objects are still being placed through the 'Tree' objects. I'm using tags to differentiate between 'Ground', 'Tree', 'pickable', and 'ghost' objects.
i have a problem with the object going through the ground and is set to valid to build aswell.
added a detection logic to my constructable script.
Constructable script:
https://gdl.space/oweqofizil.cs
ConstructionManager script:
https://gdl.space/capatonuku.cs
GhostItem script:
https://gdl.space/eqegaqulop.cpp
As in current position?
i want to rotate the camera if the mouse is moved
and i was wondering if there was an input.getmouse or something like that
yes,
I believe input.getaxis? I might be wrong haven't used that in a while
GetAxis or GetAxisRaw
does it work for mouse too?
(Mouse X) Mouse Y
input.getaxis("Mouse X")?
actually theres probably not a axis and a raw axis.. but yea Mouse X
its in ur input settings in the preferences or w/e if u wanna see the correct names
I wouldn't use a "ghost collider" for this - just use OverlapBox directly. Note that the collider itself won't ahve its position updated every frame, only during the physics sim. This makes it unsuitable for any purpose here - including determining the position for the OverlapBox
Yeah, you can check in project settings which keywords you can use with input
I've wanted to break the code into pieces as small as possible, assumed that would be the better practice
mouseAxisX = Input.GetAxis("MouseX");
In the end I won't be using these controls anyway, I will be using a grid map for the AI and move both the character and the mobs from tile to tile.
I have found this article while researching about the AI, it is amazing really.
https://www.todayifoundout.com/index.php/2015/10/ghosts-pac-man-work/
It can be, but at a certain point it can become bloated and less performant. There is a balance
Yours was fine. The main change to look at is what I changed the rotations to correspond to
the ones you had for left and right I put as up and down (and vice versa)
{
mouseAxisX = Input.GetAxis("Mouse X");
mouseAxisY = Input.GetAxis("Mouse Y");
transform.Rotate(mouseAxisY, mouseAxisX, 0);
}
is this right?
Mouse X not MouseX
mb
and may as well put those directly in the Rotate call if you don't use them anywhere else
ya, that'll work (may need modified a little to get the outcome u expect)
transform.Rotate(Input.GetAxis("Mouse Y"), Input.GetAxis("MouseX"), 0);
(if that is the order you wanted)
Yeah, I noticed. The directions are like that due to the prefab I made.
Ahhh, ok. Was it a model from blender?
nah, just basic sprites
Oh ok. Well, if you had it the way that worked, then keep on with it!
Will do. Thanks again
i thought if you wanted to rotate something horizontally you would have to use the Y axis, if you wanted to rotate it vertically you would have to use the X axis, this is what i used
Not sure what you mean. I did it exactly the same as you had it, just compressed it
yeah
but you asked me if that was the order i wanted to use
so i used first the x axis to rotate it vertically, then the y axis to rotate it horizontally
I didn't ask, I stated. But no biggie. I understand
i have to invert the value for the y axis, but why?
(if i scroll to the left, the camera srolls to the right)
just multiply it by -1
iono.. why tho
that's what i did
but why do i have to inver those values?
idk, for sure.. debug the values that those variables return.. and compare that to ur logic
im sure u'll figure out why
ik what x and y are in maths and physics
it's just odd that i have to inver the value for the x axis
well in math, moving right would be Positive and moving left would be Negative (as far the x axis goes)
this also depends on where the origin is.. is it on the bottom left corner? is it in the middle? is it dependent on where the movement starts? not totally sure, but thats why i said to debug the values.. visual confirmation always helps understanding
could also be dependent on the thing ur moving.. does the object start upside down perhaps?
lots of variables
why is the camera rotation so strange?
i am not talking about moving, but about rotating around the x axis, that fells strange, i don't get why do i have to invert it and only for the x axis
They meant moving the mouse
you should look at examples / tutorials / etc and see how they do Mouse Look movement..
usually ur rotating a child object one way and the parent another way.. so 1 object only moves in 1 dimension..
this helps prevent odd movements, and gimbal lock etc
in this example the camera is parented to the capsule.. the camera only moves up and down... it's the character (capsule) that moves on the X (horizontal)
and it only rotates when the main object rotates?
left and right (yes)
yeah mb
the camera up and down moves the child (inside the capsule)
"Mouse Look" is the terminology if u wanna look up some tutorials or something
i am gonna make a bad example, but when i used to play fortnite i remember i could use the camera and the movement in 2 different ways
would i make multiple gun containers for multiple guns?
ty
and in ur example make sure ur moving the correct way, theres local movement and global movement.. say u rotate ur camera to the left.. and then up and down.. if ur moving it (globaly) the axis never changes.. up is always towards the sky.. so if it rotates to the left or right first (like roll on an airplane) and then you rotate it upwards.. the side of the camera facing the sky would get rotated upwards.. (not the camera's original up)
if that makes sense
it does
i have script to turn on light when im near lightswitch and press e but idk why i can switch the light whereever i want and it only works normal after my first contact with the lightswitch
using UnityEngine;
using UnityEngine.InputSystem;
public class lightSwitch : MonoBehaviour
{
public GameObject inttext, light;
public bool toggle = true, interactable;
public Renderer lightBulb;
public Material offlight, onlight;
public AudioSource lightSwitchSound;
public Animator switchAnim;
// Animator parameter name for controlling the press animation state
private static readonly int PressHash = Animator.StringToHash("press");
void OnTriggerStay(Collider other)
{
if (other.CompareTag("MainCamera"))
{
inttext.SetActive(true);
interactable = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("MainCamera"))
{
inttext.SetActive(false);
interactable = false;
}
}
void Update()
{
if (interactable && Keyboard.current.eKey.wasPressedThisFrame)
{
toggle = !toggle;
// Set the boolean parameter in the Animator to control the animation state
switchAnim.SetBool(PressHash, toggle);
// Optionally play a sound here: lightSwitchSound.Play();
}
// Update light and material based on toggle state
light.SetActive(toggle);
lightBulb.material = toggle ? onlight : offlight;
}
}
this is the script
use hastebin
you'll learn the caveats of it as u work on it
what is hastebin
i am not a native english speaker (as you've seen) but i could understand what you said so far
!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.
^ its a copy-paste website.. it'll give u a link to send
go to hastebin, put the code in, save, and share url
oh ok sec
your english is plenty good enough for us to understand you š
i am gonna improve it i promise
lol
good good š
would i make multiple gun containers for multiple guns?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
then disable and enable the child object that represents the gun
then u only need to move around the parent object
is there the camera movement in the junior programmer pathway in learn.unity? i am currently at unit 3 and it would help to have it there
or u can even get more complex and instantiate and destroy the guns, but its cheaper to enable/disable than to spawn and destroy
i have script to turn on light when im near lightswitch and press e but idk why i can switch the light whereever i want and it only works normal after my first contact with the lightswitch
https://hastebin.com/share/okafepagoh.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
cant find the problem
almost positive it would be covered somewhere in the learn material
okk ty
why do you use Stay? wouldn't it be simpler to just use Enter and Exit?
i mean i can but does it fix the problem
not sure.. it could
but even if it doesn't its better for triggers like that
if u have an exit might as well use a Enter.. rather than a Stay
stay runs every frame..
i see yeah noted im gonna change it now
@rocky canyon how did you learn unity?
i don't have unity open so i can't test but i'll fire it up in a min
- unity learn
- youtube tutorials
- installing sample projects and checking out the code on my own
- making small demo's
- this channel
- friends
maybe you need ur boolean to start as false or true or w/e you need it to be
it should be off Until you enter teh trigger.. if it starts as on or w/e state is needed to enable the light, you'll be able to flip the light on until u enter and exit the trigger
(my guess w/o looking into it too deeply)
oh truu
thats the probleeem
i fixed it
thaank you
no prob š
yup, thats a common mistake. the inspector will override the values u have in the script
for him interactble was tru so pressing e activtes the light
its been a journey for sure.. it doesn't happen all at once.. im getting close to 2 years w/ unity
ok i did the thing you said for the containers, how can i make it so it doesnt follow my camera? i have the pick up controller make it not equipped
so im trying to export my model from Maya to Unity using FBX but the model always lacks textures despite exporting with "embed media". How do i fix this?
Hey guys, if I create an IEnumerator like that it should make it true and 1sec later false right? because it is not working
private IEnumerator loadSuccessText(float wait){
loadSuccess.gameObject.SetActive(true);
yield return new WaitForSeconds(wait);
loadSuccess.gameObject.SetActive(false);
} ```
it turns into true but never false
What debugging steps have you taken to see if this runs
Sounds like either:
- the object the coroutine is running on was destroyed/deactivated
- Timescale is 0
umm, if its a child it will always follow around the parent (container)
to not make that happen you could
- set its position manually every frame.. transform.position = (place you want it) and then you'd have to have logic to set it to the parent's position and then stop manually changing its position
or - you can set its parent to null in the code (that will unattach it from the parent) - it will no longer follow it around
then when you need to - you can set its parent to be the player or gun holder or w/e (set its position to the place you want it)
then it'd follow it around as a child normally would
not exactly sure why you wouldn't just keep it where it is.. (if you have no guns you can just disable all the guns)
when you DO have a gun you just enable it.. and it will already be parented and where it neeeds to be
the weapons you pickup should not be the same as the weapons your character has..
(that'd be the only reason i can think of as to why u wouldnt want them just to be attached all the time)
the pickup gets destroyed.. then ur script just does some logic to let the player have the weapon (be able to enable it)
What are all the ways I could use to repeat a certain part of code a certain amount of times?
for context, I am making a spawn point for enemies, where the game repeats the same line of code multiple times via calling the same private void in the script multiple times.
my problem is that I don't know the proper way of doing it, since using a while loop often freezes Unity itself when it gets called via the player touching an object that tells the enemy spawnpoint to activate the spawning code lines (unless I get rid of the enemy-counting code which is in Update).
for loop
Yep just a for loop
using a while loop often freezes Unity itself when it gets called
This just means you messed up and wrote an infinite loop
why my CC .isGrounded is returning true and false rapidly? How this check works, why when CC is on ground it returns false
You're probably calling .Move twice in one update
a.k.a. The Brackeys Error
isGrounded becomes true when the most recent Move call pushed the CC into the ground
why is it called the brackeys error
once
Becasue Brackeys did it in a video like six years ago and basically every tutorial ever since has just copied his code
ahhhh ok, well I guess I never truly figured out how to edit a template of a for loop so I just went for an option that sounded better (simpler) in my head...
its been a while since I made loops anyway.
so it will be better to make own groundcheck?
show code
I am already refactoring it and that's why I noticed that my cc isGrounded returns true and false
private void FixedUpdate()
{
if (!IsOwner) return;
isSlopeTooStep = CheckTooStepSlope(); // This should be in GroundMove or something...
if (WantToCrouch())
CrouchMove();
print(_controller.isGrounded);
if (_controller.isGrounded)
GroundMove();
else
AirMove();
if (CheckCeilingHit())
{
Debug.Log("HItted Ceiling!");
playerVelocity.y = -0.5f;
AddGravity();
}
/* Calculate top velocity */
Vector3 udp = playerVelocity;
udp.y = 0.0f;
if (udp.magnitude > playerTopVelocity)
playerTopVelocity = udp.magnitude;
playerVelocity += baseVelocity;
_controller.Move(playerVelocity * Time.fixedDeltaTime);
playerVelocity -= baseVelocity;
Show the full script. !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.
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.
In GroundMove, you set the player's Y velocity to 0 if they're grounded. This means your next call to .Move doesn't touch the ground, and thus sets isGrounded to false. Instead of setting it to 0, set it to a small negative number so it touches the ground
works, thanks!
ok, it's not
i got an prefab object and i want to intantiate a gun object as child of this prefab so i get the gun to move with the prefab but got this error
u got to set its transform to the Instantiated prefab in the world..
not the actual prefab
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce), ForceMode2D.Impulse);
would that be how i do ImpulseForce
You should set the parent of an object that exists, instead of a prefab file
instance of the prefab rather than the prefab itself?
yea
im making an instance of an objectt as a child of a prefab
why
That also doesn't make sense
that's a scene object being a child object of a file on disc
to have follow movement?
A prefab doesn't move
because it doesn't exist
Having a scene object be a child of a prefab makes no sense
worked, thank
https://youtu.be/v1UGTTeQzbo?t=28 hey friends, im having a gander at this vid and in it, the person is giving his enemies each thier own canvas so they can display thier own health bars. I was under the impression giving individual objects their own canvas was poor practise? can someone please advise
In this video we cover 2D enemy health bars for Unity and C#
This video is part of our "In 5 minutes" series where we show you exactly what you want to know.
SUPPORT GREAT CONTENT
https://www.patreon.com/DistortedPixelStudios
$3 = Coffee with P...
Actually, the bad practice is putting everything on the same canvas
i believe it is. (UIs being updated and redrew all the time is why it would be taxing)
also I believe games recycle UI panels for in world characters and stuff like a pooling system where it only uses what it needs
i haven't seen many games with a huge amount of healthbars.. altho one game comes to mind specifically and its a simple 2d game with a huge amount of enemies and stuff going on.. and theres tons of healthbars
its a top down point and click battle shooter type game
I'm guessing this only becomes a problem when you have hundreds/thousands of canvas' and elements on at the same time?
id guess lower but ya, and ur logic..
how ur updating them
plays a role also
instantiate 100s of ur prefab with an empty canvas and see what the performance does.. go from there, same with a smaller number
ok thanks for the advice!
whats a good way to learn unity coding
!learn
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
lots of practice
ok i wanna get good at it so i can make games with out looking at tutd
My personal advice, after getting familiar with the basics and maybe making some of the Unity Learn projects or your own small projects, you could look into programming patterns and S.O.L.I.D architecture - its a bit more of an advanced topic, but I found just getting familiar with a few patterns helped bridge the abstract "I wanna make this cool thing" and "where do I begin in making this cool thing?", then maybe try to apply that to something like pong, breakout, small projects like that, though through trial and error you may find an approach that works well for your understanding and workflow
Is there a good reason why this math isn't working?
The code being print to console is this:
print("ammoInClip: " + ammoInClip + "\nclipCapacity: " + clipCapacity);
print(ammoInClip / clipCapacity);
if you want a float as the result, you'll have to cast the ints to float
so convert the ints into floats beforehand?
Yes.
So I'm trying to reference my Paddle position to this Projectile script so I can get it's position... where am I going wrong?
I'm getting a null reference to the m_paddle but m_paddle does in fact exist
you never assigned the variable to anything. in fact it's readonly
to the paddle I would assume
make it public, not readonly, and drag+|drop
you know this by now
awesome, thanks
how do I "shoot" the projectiles?
Like grant them movement shooting up
Set velocity or apply forceš¤·āāļø
Put a script on them that moves it
So I'm trying to apply force however I'm getting that null reference error again despite having a RigidBody2D attached to it. Oddly enough it disappears during play. What am I doing wrong here?
Oh I think I need to give my prefab a rigidbody not the spawner
if (Input.GetButtonDown("Fire1"))
{
// Instantiate projectile at the position and rotation
Instantiate(m_projectile, m_paddle.transform.position, Quaternion.identity);
rb2D.AddForce(transform.up * thrust);
}
So I'm trying to apply force upwards but what's happening is that it's dropping down, any ideas?
If you didnāt do it you need a public rigid body save it in your script and drag that rigid body onto your script
Gravity is set to zero
I'm having trouble with AddForce now
Use Impulse mode. And what is thrust set to?
What's impulse mode? And thrust is set to 1, but I tried 10 with the same result of it just dropping down
Is that in the projectile script?
Yes
Are you sure about that? Why are you spawning a projectile in the projectile script then?
Well this is the projectile spawner
It just generates projectiles upon click
Then I want to apply a force to it
So it's not the projectile script..?
Nope it's the spawner
It's the second parameter of AddForce.
1 for thrust is pretty low too
https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
Oh yeah, you aren't adding the force to the projectile
Ok, then what does the rb2D reference?
Instantiate returns a reference. Get the rigidbody from that
while (true)
{
transform.LookAt(target.position);
transform.position += transform.forward * _followSpeedCurve.Evaluate(followSpeed / timeElapsed);
timeElapsed += Time.deltaTime;
yield return null;
}```
How would I be able to get the followspeed to ramp up based on the curve of this coroutien?
what you have is fine but you do need to multiply the speed by deltaTime
ok ill try it out thanks
Although this makes no sense:
followSpeed / timeElapsed
it should be timeElapsed / duration
the thing is I dont have a duration in this case
it would be the duration over which you want the acceleration to happen
I just want there to be a set speed rather than reach a destination wihtin x speed
what about this? _followSpeed * _followSpeedCurve.Evaluate(timeElapsed)
this is equivalent to timeElapsed / duration where duration is 1 second
it's also unclear what the followSpeed variable is in that example
thats the speed of which the transform will move, well the base speed.
it gets modified based on the animationcurve
so the curve is supposed to be a speed multiplier?
yes
oh i forgot to mention as to why i didnt use duration here but i see what it means, duration is the max value. I want the coroutine to keep going.
float maxCurveValue = 1;
while (true)
{
transform.LookAt(target.position);
transform.position += transform.forward * (followSpeed * _followSpeedCurve.Evaluate(timeElapsed / maxCurveValue));
timeElapsed += Time.deltaTime;
yield return null;
}```
seems to be working, i want it to keep following until it collides to the target
this is just duration of 1 second
the coroutine is going to keep going forever because you have while(true)
yea i want it to keep going until it collides
the duration in my example does nothing besides decide how long it takes to accelerate
that's what the duration is for
it's the time it takes to go from followSpeed to whatever the max at the end of the curve is
ahh i see
Hi, I had this issue yesterday, and I thought I could fix it by clamping the fall speed, although it is persisting. I would appreciate any help or information as to why this is occurting. Please ask if you need more information. Here is my current code https://paste.myst.rs/hi3j0h3a Thank you.
a powerful website for storing and sharing text and code snippets. completely free and open source.
How do I get the reference from that?
put the Instantiate call on the right side of an assignment operator
GameObject go = Instantiate(prefab);
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
var instance = Instantiate(prefab);```
GetComponent
Same way you get any COmponent from anything. GetComponent
Oh yeah component
or spawn based on the rigidbody
public Rigidbody prefab;
Rigidbody newRB = Instantiate(prefab);
unless of course prefab IS a Rigidbody reference already
if (Input.GetButtonDown("Fire1"))
{
// Instantiate projectile at the position and rotation
var instance = Instantiate(m_projectile, m_paddle.transform.position, Quaternion.identity);
instance.GetComponent<Rigidbody2D>().AddForce(transform.up * thrust);
}
Hmm no dice...
no, var is fine
oh okay
What isn't working?
doesn't look like you DO anything with it
It's not shooting my projectil up
Show where you try, nothing there shoots it up
is the rigidbody kinematic
Oh, I totally misread it
doesnt kinematic just make it not detect collisions?
No
then make sure they aren't perhaps colliding with something
Kinematic makes a rigidbody not respond to forces, but can still exert them
oh so like it self will exert force on the object but wont be effecte by them?
is thrust still 1?
0,1,0 * 1 is 0,1,0....
It might have something to do with it spawning directly on top of my player object
put it on a layer that does not collide with the player object
Thrust is 10f
also you probably want to use ForceMode2D.Impulse
I was gonna say, you didn't do that yet
See the different force modes here:
https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
so adds the force instantly
Oh ok, good good
Turning off the rb would DEFINITELY make it not work
No no, on the player object.
do both objects have colliders?
In case it was colliding with the projectile to test
Did you do Impulse mode yet?
What happens right now? Do they just fall?
Yeah
if its falling then just set gravity to 0 no?
do not multiply your forces by deltaTime
Do that, and make thrust like 100
Just to test
What is the MASS of the projectile?
And yeah, definitely do NOT do deltaTime here
if its falling down... then it might be because thurst.up?
isnt that on y axis?
could thrust be making it negative somehow?
if you are working on 2d it would be forward i think right? but on 3d it would go up and down
sorry if i am making this worse lol i am trying to learn as well.
All good we're trying
That actually is a good point about direction.
@dense root
Try this just in case:
instance.GetComponent<Rigidbody2D>().AddForce(Vector2.up * thrust);
That uses the world coordinates and wont be affected by any transform rotation
might as well do Input.GetAxis("Vertical")?
No. They aren't using input for this.
They are shooting a projectile
Ohh i see
but then vector2.up wouldnt help no? isnt that just (0,1,0)?
i mean 0,1
It might help if I shoot a video of it all
correct.. it is "up" which is the way they want to shoot it
This is a galaga game. They hit a button and it shoots a projectile up from wherever they are
wait no
you need to grab the ridgid body of the instantiated object no?
line 23
on start you are setting it to the original object
why are you adding a Rigidbody to the spawner?
wait i am so confused
and what ahppened to your instance variable?
What happened to the code we've been working on? This is not what you want at all
And everything that was discussed above lol
yeah lol
This?
if (Input.GetButtonDown("Fire1"))
{
// Instantiate projectile at the position and rotation
var instance = Instantiate(m_projectile, m_paddle.transform.position, Quaternion.identity);
instance.GetComponent<Rigidbody2D>().AddForce(transform.up * thrust);
}
Yeah. Why was that not the code in the video?
it should be an Impulse force too