#💻┃code-beginner
1 messages · Page 449 of 1
it can be savage in here somedays
Mostly new users
My keyboard and screen is abotu to be broken
its 5 in the morning
im still trying to learn ai
without knowing unity
oof, not a good combo
- Step 1
Its time for me to sleep ty for help @rocky canyon i'll read the article when i woke up
if(camPos.y < 0.0) Debug.Log("I am below the camera's view.");
if(1.0 < camPos.y) Debug.Log("I am above the camera's view.");``` so the debug.log and is firing when the sqaure is already half way off the screen and I think this is due to the transform.position the position must be in the middle of the square for the log to be triggering half way any idea on how to fix ?
Instead of checking 1 point(the position), check the bounds or their corners.
do you mean in the if statements ?
😦 tried to switch over to using a ObjectPool and after setting it all up first thing off the bat I get a stackoverflow exception
Well, no. It wouldn't be one change. You might need several if statements or use some API that checks rect/bounds intersections.
Probably a recursion somewhere.
got it
this worked SpriteRenderer renderer; renderer = GetComponent<SpriteRenderer>(); Vector3 topRight = renderer.transform.TransformPoint(renderer.sprite.bounds.max); float verticalInput = Input.GetAxis("Vertical"); transform.Translate(Vector3.up * verticalInput * _speed * Time.deltaTime); Vector2 camPos = cam.WorldToViewportPoint(topRight); if(camPos.y < 0.0) Debug.Log("I am below the camera's view."); if(1.0 < camPos.y) Debug.Log("I am above the camera's view.");
Ill just change it for the bottom one too
seems the first Get call calls create several times, is that an expected behavior to fill up the initial capacity?
No clue what get or create calls you're talking about. I don't have access to your code.🤷♂️
Nor do I know the details of your pool implementation.
ok was about to paste the code, but I think I see the recursion now
Is pooling one of those things that almost always boosts performance, just sometimes a negligible amount
Are you asking if there are cases where it can hurt performance?
I'm trying it because in my case spawning up a new object was a heavy hit on memory each instantiation, a minecraft like chunk of blocks, so much data had to be new'd up for each
My basic ObjectPool setup
chunkPool = new ObjectPool<GameObject>(
() => { return Instantiate(chunkPrefab); }, // create
(GameObject) => { GameObject.SetActive(true); }, // get
(GameObject) => { GameObject.SetActive(false); }, // release
(GameObject) => { Destroy(GameObject); }, // destroy
false, // collection check
10, // capacity
50); // max capacity```
though I get no more errors now, it's not working right, so more reserach 🙂
Yeah, basically
Well, if it's configured correctly, then there aren't cases like that.
If not configured correctly, your pool might be eating more memory than necessary.
Other than that, there are cases where the benefit is negligible.
Got it 👍
You are trading cpu time for memory allocation when you pool. Memory is almost always at less of a premium. Taking less time on the cpu is almost always good.
If that is not the case, there are probably other significant issues to be addressed
Wait, do memory allocations get cleared during runtime at some point
Can someone direct me to an article about this stuff for unity
DURING runtime? Only if all references are dropped, or told to directly
Google c# garbage collector
Ah ok, garbage collector
this is a great use case for object pools. If it's not working right, 9 times out of 10 it's usually how you're resetting the objects. If some state isn't reset or overridden when you get it from the pool, you end up with weird behavior.
that or how it's decided to release objects back to the pool
this is going to be trickier than I thought, going to want to skip some steps in the startup code for a chunk, but some definately will need to occur since the data will be different per chunk. Mainly I wanted to stop the horrendos new calls each time
I guess I need to look into what SetActive(true) actually invokes, I blindly copied it from a video
SetActive is the same as clicking the enable/disable toggle on a game object in the editor. It invokes OnDisable() and OnEnable(), and when a game object is disabled, none of its components or that object's children will run their update loops.
right now all my new up code and populate chunk is in Start(), guessing what I need to do is split that up and put the memory newing into a seperate method, and check if already newed up if so skip
whats the issue?
missing a semicolon per the error and screenshot
and what is that line with public Rigidbody = rb; between hte class and it's brace...
this is the ss from brackey's video
well you copied it wrong
And it's different from what you have
Might want to learn about the basic C# syntax so that you don't miss small things like that.
don't know why people want to learn 2 major things at once, C# and Unity both deserve their own time
Usually I stick a Reset() method the class I'm pooling, and then call it in the Get wrapper for the pool:
public class ChunkManager
{
private ObjectPool<Chunk> pool;
public Chunk GetChunk(args)
{
var chunk = pool.Get();
chunk.Reset(args);
return chunk;
}
}
i had learnt it in school like 3 yrs ago yk any sites or videos to re-collect it?
There are plenty if you google.
This one for example:
https://www.w3schools.com/cs/index.php
I'm trying to spawn an object "missile" behind something which is put in an array.
How do you do that?
please post that !code again
📃 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.
also that instantiate makes no sense
none of the code makes any sense
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Instantiate returns a copy of an instance, use that
I tried to follow, but is that how it work?
not exactly no.. did you see both examples ?
read the bot message if you expect help
Yeah
clearly not
- why are you using a specific number for vector3 and also why is not a variable, also its not written correctly hence the error
- why are you not using the clone/copy returned from instantiate to put it in array if that was the end goal
- I tried to grab the position of the object that I wish to put it behind it but I've decided to do it manually.
- Huh?
also you're passing a position as Object, the more i look at this the worse it gets tbh..
nvm misread that as wanting to add it to an array
anyway read the docs i sent how to properly write Instantiate
also don't post code as screenshots
Alright, I'll re-read them
btw the coroutine is also doing nothing right now and its not properly called
Hey, I have clamped input values (middle mouse button for pan), but when reading and logging values, I see larger values!
ReadValue<Vector2>
Can't help without !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.
How do I ungroup object in unity? I tried making parralax effect but it seems like all my object still moving together even though the code tell them to move on different speed
private void CheckMovement()
{
var value = _movementInputAction.ReadValue<Vector2>(); //here value is not clamped while it should be. I have added clamp in post processing section (new input system)
foreach (var cam in _cameras)
{
var panSpeed = Mathf.Lerp(_panSpeedRange.Min, _panSpeedRange.Max, MathUtility.Remap01(_zoomRange, cam.GetZoom()));
cam.transform.position += new Vector3(value.x, value.y, 0) * Time.unscaledDeltaTime * panSpeed;
}
}
It is called in Update
When I add the line below, it is OK
value = value.normalized * Mathf.Clamp(value.magnitude, 0, 10);
but why doesn't post process in input window work?
public class ParalaxScript : MonoBehaviour
{
private float length, startpos;
public GameObject cam;
public float parralax;
void Start()
{
startpos = transform.position.x;
length = GetComponent<SpriteRenderer>().bounds.size.x;
}
void FixedUpdate()
{
oat dist = (cam.transform.position.x * parralax);
transform.position = new Vector3 (startpos + parralax, transform.position.y, transform.position.z);
}
}
```
its not even moving... im so confused
im trying to understand this but i still dont get it..
When you move the parent, any object without dynamic physics components moves with it. Look at the parent as a folder instead. Move only children.
I put this script on layer 0 until 4...
the children of it I just ctrl c and V to extend it
You'll get more control with single script. Put all panels into a single array and move them together. If one reaches outer bounds swap it to new position.
Note you can also have just one tiled large sprite and just animate material offset to move it back and forth
Recommend me a tutorial to learn unity?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I thought it was going to be a yt video lol
If you want to learn properly without wasting your time you should follow Pathways courses on that page.
I wanna make steam inventory items but i dont have a project yet and dont want to pay 100$ for it how can i test without buying yet
Abstract methods, then you can swap them for real thing when you need to
You read how their API works and simulate that. https://partner.steamgames.com/doc/features/inventory#APIs
okay thanks 😄
!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.
yo guys any tutorials and documentations on how to code 3rd person camera without cinnemachine
Don't crosspost.
Did you try googling it? There are plenty of tutorials on that topic.
Yes
i tried
only cinnemachine tutorials
Are you sure you looked at all beyond the first search result?
I've just tried googling and there were several(as soon as the second search result) results not involving cinemachine.
That being said, I'd still recommend using cinemachine.
yes
Btw
i have so many public variables
but it only shows 2
which arent even ther
in my scrip
It doesn't even look like it's the same script(all of the fields are different).
Do you have compile errors in the console?
Is the player movement + jump code too basic as a foundation?
I'm following from this tutorial: https://www.youtube.com/watch?v=CxyV_dVZVas
In this video I show a really easy setup to get you started with the new input system in Unity.
Intro: (0:00)
Overview: (1:18)
Step One: (1:22)
Step Two: (1:49)
Step Three: (1:57)
Step Four: (5:11)
Mainly plan to add a double jump, dash and run slates for the code.
The simpler the better, it doesnt matter what it is at the start, just add on and modify it to your future needs
Ok
Ok i can see them now
see the errors
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMain : MonoBehaviour
{
public Transform player_core_transform;
}```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerOBJ : MonoBehaviour
{
public Transform playerCoreTransform; // Player's core transform
public Vector3 positionOffset = new Vector3(0, 2, -5); // Camera position offset
public float orbitRadius = 5.0f; // Radius of orbit
public float rotationSpeed = 5.0f; // Speed of orbit rotation
public float maxZRotation = 20.0f; // Maximum Z-axis rotation
public float minZRotation = -20.0f; // Minimum Z-axis rotation
private float currentRotationX = 0f; // Current X-axis rotation
private float currentRotationZ = 0f; // Current Z-axis rotation
void Start()
{
if (playerCoreTransform == null)
{
var player = FindObjectOfType<PlayerMain>();
if (player != null)
{
playerCoreTransform = player.player_core_transform; // Ensure this matches your actual PlayerMain definition
}
else
{
Debug.LogError("PlayerMain script not found in the scene!");
}
}
}
void Update()
{
if (playerCoreTransform == null) return;
// Get mouse inputs
float mouseX = Input.GetAxis("Mouse X") * rotationSpeed;
float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed;
// Rotate around the player based on mouse input
currentRotationX += mouseX;
currentRotationZ = Mathf.Clamp(currentRotationZ - mouseY, minZRotation, maxZRotation);
// Calculate the new position and rotation
Quaternion rotation = Quaternion.Euler(currentRotationZ, currentRotationX, 0);
Vector3 offset = rotation * new Vector3(0, 0, -orbitRadius) + positionOffset;
transform.position = playerCoreTransform.position + offset;
// Look at the player
transform.LookAt(playerCoreTransform.position + positionOffset);
}
}```
oh wait
i fixed the issue
why I have that many issue and why does it give me errors when I put the ";" correctly?
Assets\_Script\Multiplayer\Client.cs(202,106): error CS1002: ; expected
i have a problem.
blue is the player, red is the AI, orange is the AI's line of fire, green is the direction the AI should go.
whenever the player gets on a place that is higher than the place the AI stands on, the AI's line of fire can be blocked by whatever the player is standing on and thus can hit them.
i want it to find the position it should move to in order to be able to target the player, but i dont know how to do that
I cant understand any docs, i tried, eveyr tutorial, on cinnemachine and stuff, i know the basics, but this math, quaternion and stuff is soo confusing, i can make basic games and 1st person camera, but 3rd person is out of my leuge cuz maths
I'm guessing IAttack is an interface and interfaces are not serializable
well i thought serialize reference help that
You need one after setting kills as well.
you might want to look at
https://github.com/mackysoft/Unity-SerializeReferenceExtensions
Learn the math then.
If you use cinemachine, you don't need to deal with the math as much(if at all), though.
Probably because nothing is assigned. You need an actual instance of an actual type that implements the interface assigned(via code, since there's no way to assign it via the inspector by default)..
awh
Oh thx !
guess i can use abstract class instead?
ahhhhh was alittle confused but i manage to figured out what you mean
Hey, this is an interesting problem you are presenting. Unfortunately, there isn't an easy solution to this using Unity's navigation system.
I think your best bet is to have pre-placed visibility markers for your AI so they can have points where you know they can see the platform. The process would be:
- Get the closest visibility marker to the npc.
- Raycast the marker to the player.
- If hit, navigate to that marker position on the navmesh. If not hit, get the next closest visibility marker and repeat.
This will require placing visibility markers which will add to your level design time. However, a dynamic solution without markers would be a lot more complicated. I had an idea for that and I can go over it if you want, but I think the marker solution is a lot better.
Hopefully that makes sense, let me know if you have questions.
nah dw i just played some DUSK and realized that in that game if enemies get into that situation they just chase the player, and if they cant get to the player they can just get cheesed lol.
if DUSK can get away with it then so can i
Okay, fair enough. lol
There is actually a solution to this situation using Boxcasts if you want to hear it
nah, its the first "smart" AI ive ever written, i wanna keep it simple before im comfortable making it more complex. if it means that it can be cheesed, what game doesnt have an AI that can be cheesed? lol. thanks for the offer though
!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.
Here's my movement code as of now: https://hastebin.com/share/wibitigice.csharp
Mainly focusing on these two:
void OnJump(InputValue value)```
For OnMovement I plan to add a minSpeed + maxSpeed, a Dash and a RunSpeed.
For OnJump, I plan to give it gravity, a grounded function and a DoubleJump.
How do I add in the ``GravitySettings`` and ``GroundSettings`` to ``void OnJump(InputValue value)``?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you have 2 nested classes so the first thing you need to do is create instances of them
because you dont have a varaible called body
Can I make a Canvas instantiate itself according to the players position?
Exactly what it says
Should I worry?
yes
change your path names. paths should only contain A-Z and 0-9
One example would be this:
{
Vector3 spherePosition = transform.position;
spherePosition.y = transform.position.y + GroundSettings.SphereCastRadius - GroundSettings.SphereCastDistance;
bool isGrounded = Physics.CheckSphere(spherePosition, GroundSettings.SphereCastRadius, GroundSettings.GroundLayers, QueryTriggerInteraction.Ignore);
return isGrounded;
}``` As the variable called body for isGrounded
rofl, that message was not for you but someone who deleted their message
Oh
Any notes for mine?
so gamers, whats the best way to do racing ai? making a mario kart clone and just thinking about all of the drifting and turns makes me think of using a bunch of colliders to tell the ai what to do, but that is really cumbersome especially if i have a lot of maps
it would be more convenient if you built your track with a spline. have your cars follow the spline with an offset
to get very technical, mario kart rigs their races a lot such that
- players who are first at the start of the race fall behind a lot
- players in the middle of the race are given equal opportunity to catch up
- last places tend to receive better boosts and racing AI becomes much more difficult
but I don't think you're thinking of that here. As long as you get the car to follow the spline it should be fine
i'm just thinking about having a basic racing ai that could potentially use the drift functionally so that i pass the class
Unity is really fun and easy but its so damn time consuming
Ok
especially when it comes to finding assets ;_;
but thanks for the valuable info gamer, I'll look into splines
nintendo rigs all their party games. mario party especially, theres a set of narratives that play out every game. including first place players getting screwed over at the last minute, last place players suddenly making comebacks
these are small things that make mario party and mario kart much more memorable than something that's just randomly generated, yet consumers dont know about
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hi all, Im running into a bit of an annoying logical issue hoping if someone can help:
I have a player with grid based movement. There is two item, Item A and Item B.
When player step on an Item, it picks it up, follows the player.
And when the player with an Item, steps onto Item B, it switches to holding onto item B.
Now I don't want the item to switch indefinitely (since both Item A and Item B are on the same tile as the player, and the colliders/triggers are activating in Update)
My solution is, once I dropped the Item, it will only be "pickup-able / turn on collider" after the player has moved 1 tile
The issue is, if I want to make the player to be able to "throw" the item in an direction, how should I handle the colider? As I want the item to stop if it hits any obstacle. I "need to" turn off the collider when I first throw the object because I don't want it to instantly pick it back up.
Question: Is the way Im handling the collision good? Have you seen a better way? Thanks
You could try to have 2 colliders, the first on set as trigger which would be used to pick up the item and the second ones for collisions with the environment
hmm interesting, make sense, technically I can have two colliders and set them on different layers but on the same object
Are these triggers or colliders?
If they're actual colliders, Physics.IgnoreCollision is what you want
Turn off the collision between the player and the item while it is being held, re-enable the collision after it is thrown. Make sense?
ended up figuring out a really simple solution, basically I put a bunch of game objects that have box colliders. I keep the ai car permanently accelerated and steering (rotating) towards their next waypoint. Waypoints get changed on triggering box collider
that works
though the car wont exactly follow the road smoothly
make sure the cars are offset from each other so they dont go to the exact same spot
when it comes to balancing also dont make every car take the tightest corner otherwise your players cant overtake them
is there a way to mkae a variable show in the inspector but read-only?
[ReadOnly] public int Example;
trying to make attack animations work for my school project, and the code didn't work but now I have this perpetual error and I have no idea what it means
UnityEditor
its a unity bug, clear it, ignore it, or restart the engine
already done, thank you!
Can I spawn a canvas according to the players position even if it is UI related?
for example I want to show the inventory next to the player
If it's a world space canvas, it has a world position. So yes.
If it's screenspace, then you can't move the canvas. You can however move the elements (for example, the inventory panel) and position it with code to be where you want relative to the player.
ArgumentException: The Object you want to instantiate is null.
UnityEngine.Object.Instantiate[T] (T original) (at <f1e29a71158e46cdb750140a667aea01>:0)
SpawnCharacter.Start () (at Assets/Scripts/Character Scripts/SpawnCharacter.cs:13)
Getting this error when trying to spawn the character from CharacterManager even though I do have a default character prefab at Index(0) of the char manager
Am I doing something wrong here ?
It's trying to instantiate whatever is in the Prefab field. Not sure why indexes would have anything to do with it?
Yes... I'm so trippin right now.
As for the index, that's because I am using a characterDB like this:
So, it should instantiate cat, but it's not
Heck... even the name of the current selected character is good but it's not spawning the prefab
Whats in Charactermanager.Prefab?
The prefab of the selected character.
I have made it a property
if its a property how did you add the Prefab to it
This function does the job
It's on the same gameObject
By default, it loads character at index 0
It's clearly trying to instantiate before it sets the property value since it prints the error before the name
You must be running the previous method before this function runs
But I have RequiredComponentEnabled 😬. Lemme try placing UpdateCharacter code in Awake(); and instantiation in Start(); of the other script
correct, that order will fix
Yes!
RequiredComponent just simply slaps the Component onto the object if its missing
Now to fix the position and rotation of the character 😂. But at least it's working.
it has nothing to do with order of methods
But I also read somewhere that it waits if the component is attached but not awake
So this is perfect that it waits until char manager is awake, then does this
by the way , this is the outline on how unity deals with events timing
https://docs.unity3d.com/Manual/ExecutionOrder.html
I've read that but yk... kinda dum dum of me to assume that both of them should be in Start
just a bit
there is no guarantee which Start will run first unless you mess with Order of Execution
Awake <-- Set up self
Start <-- Grab stuff from others
I think it goes by the ID but not too positive
That is, by spawning an object after another. That's the only way ig
Interesting
Ideally you want to manually control your flow execution instead of relying on unitys
yes, i use this as a true last resort to be honest
same..
I try not to use it, and work on a better design first
lots of Init() methods 😛
and events ofc
this Realistic Vehicle P... whatever..
seems he wants his stuff to run ASAP (move over unity)
lol
ooh yes. i'll definitely consider that if I ever need to have my own execution order. for now, it's working alright.
almost done with my game. only character selection giving me KIND of a hard time. It's a Basketball game for an internship lol
wow a whole game for an intership, you're quite committed 😛
better be paid intership lol
It's literally for a game development studio, what do you expect? 😂
That is not normal for a studio
It's a game jam. But all participants get a certificate nonetheless. So, yeah counts as an internship, etc.
Jams4Jobs
We're 4 group members. 2 artists, 2 coders.
I've developed most of the physics, game logic, currency system, etc.
Another programmer does the UI and linking it to the code-behind.
But right now, setting the animations is a really big deal 💀
Time to hack the NavMeshAgent and create a Rigidbody Agent 😈 wish me luck
Even harder is gonna be making the character face the right way because the prefabs that the artist sent come with preset positions.
animations are a pain
Any idea on how I can change the predefined position in a prefab without tearing it apart. It has metarig, etc. in it
if u mean the pose not really.
if u mean the orientation (can use an empty gameobject)
I had to design an animation out of an animation to make sure the character was behaving properly because the first one was really long.
are they not T-Pose?
Yes I meant the transform Position and Rotation.
ya, just tuck the rig as a child..
The pose is not an issue, I baked the poses so animations are working alright now.
Hi friends.. Just starting with unity again after some months.. still getting grasp of things again.. my old game when I open the code i see colors on things.. but in the new game when I write the code everything looks same color.. how to fix that?
!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
Okay yes. Is there a "universal" way to make all the characters face left?
no probbaly the parenting hack is the best you got
seems they are all facing Z / Forward which is quite normal as default
simplest atleast
Hmm.. so get a reference to the spawned child then rotate in script is best I should do?
no no reference needed
no..
just rotate the child (object) so its facing the parents Z direction
well the left direction
right click the object, Create Empty parent rotate to the left.
Now rotate the child as desired to match parent
w/e orientation u want lol
Yes but the character spawns at runtime. And it's different for each character ig.
you have to make a prefab, dont spawn in model directly
if they all have the same orientation you can keep the parent the same and just swap out the child accordingly
omg yes. I still have a lot to learn 🤦. But yes I got it now
Model to prefab, then fix orientation, then assign prefab to database. Will do the job
Thanks a lot y'all! Really appreciate it as a beginner 🥹🙌
does interface holds value in itself
what does that mean?
can i write setter that sets itself and holds the value
if you mean can it hold any values , no because they are simply just "contracts"
hey guys..I just clicked on the scripts folder, create new, create C# script, gave the name and tried to drag to my 2d circle object and get that error.. the classname is the same as the file name.. what could it be the prob?
There are no compile error and the file name is the same as the class
interfaces cannot hold any values
they just define contract for the implementing class/struct (methods, props, events)
values are provided by the classes or structs that implement the interface
show us PlayerBullet.cs
try just going to Assets and Reimport
nope, no errors there
I get that too sometimes when I create a new script on a gameobjec/prefab
unity just fucking up in this case
i do the spam->alt+tab dance
Ok thank you !!
also why is your IDE not looking configured 😅
he's been sent a referral, no worries
well its wierd.. if I open a script on my previous game.. it is configured.. i started a new game now and in this one the IDE doesnt look like configured.. i need to do that for every new game?
is it selected as the external code editor in the settings?
did you open the script directly in unity
also yeah check if its External Tools
might need to Regen project files a couple of times
Will check that, thank you!!
I think its related to that error.
ohh, make sure u have the updated plugin
via hte package manager
yeah been 6 months without using unity.. might be it
yeah do you have Unity and DevKit extensions ?
I should have.. if I open the scripts from my old game I get no error just in this new one I created now
its 2.0.22 now.. and they dont use the Code Editor one anymore
also make sure to remove the Visual Studio Code Editor package just to avoid any weird hooking problem
its deprecated
I see, ok thank you
one day, they'll make it all plug-n-play 😅
Got the character to spawn perfectly in position. The only thing remaining is the character animation setup. What's the best way for this though?
because now my character is spawning at runtime so I don't think I can just assign like that, or can I?
literally took microsoft to do it , which is sad Unity doesnt care about VSCode yet their Videos now feature VSCode
wdym best way ?
you probably dont want root motion on do you
ahh the ole "not my job"
seriously. aside from the bugs its hard to really get unity to do anything else
Now its working again, thank you
Nevermind. Lemme simply the question. if I assign the controller directly to the prefab, it won't arise issues for me right?
wrong tag lol
if they have different avatars you have to swap those as well, animations "should" work universally if proper avatar is set.
Dont take my word on it 100% cause I dont mess with animations too often
u should be good to go from now on.. (until u go on another break) lol
Nah the avatar is the same 1 for all of them. But if that's the case for animations, then I guess i'm good to go
mmhmm shoould work as is
should be fine using the same animator controller then
either way it would actually
Can I ask just 1 more question for now? I might be sounding annoying but... this is the last step to completion lol
Alright so... I need to access the character but... the character is...
this far
So, I should assign the "Character" now? Right?
And then access the child through it
haha yeah,, I should not have breaks .. that is procrastinate.. and I want to be a pro on that.. need to have more discipline.
Okie yes.. got it to work
Ignore the question at this point 😭 answered it myself
You cannot add scene objects to prefabs btw
thats why the Type Mistmatch usually
Obviously. In this case, I just wanted to access the animator
So, I got a reference to the "Character" (spawner), then used GetComponentInChildren<Animator>(); and got it to work
make sure u cache those types of variables and re-use the cached versions
dont know ur code.. but jsut dont call GetComponent every frame for example
via Awake() or Start() but im sure u know that
Me?
yesh u
Yes I do that in Start() or Awake() 😂
My question is : Why? 😭
ignorance
You can also access it as a property from Character(if it has a script with animator referenced) and skip the get component completely 💪
lmfao!
good to know u have critical thinking skills
to be fair I did that too in the beginning lmfao
fun fact, but while caching the result of GetComponent is definitely advised, the actual GetComponent call is very fast so it isn't really worth worrying about all that much unless someone is really going overboard
data to back up that claim by the way: #archived-code-general message
ohh sweet, "he did the math"
https://docs.unity3d.com/Packages/com.unity.test-framework.performance@1.0/manual/index.html
it's a pretty handy package
new toys! sweet
the more i learn unity the more i feel gaslit.. alot of the things i heard "NEVER DO THAT!" are more like.. "its okay if you do that a little bit"
it all started with, Camera.main
I mean, most things are okay in moderation. Like a single Find call in Awake? that's technically perfectly fine even though it's going to be slower than almost any other way to get a reference to another object. It's still better to teach people to do it the right way though
to be fair with this, Camera.main did used to be a lot slower than it is now
Honestly, I spent 1 and a half month trying to learn unity back in Decemeber 2023. And even for a month in July 2023. And I hated it. I thought it was sooooo complex.
But now, in a month's time, I'm learning and enjoying it, never thought I would 🌝. Internship coming in handy ig
ya, im not complaining by no-means..
i guess its better to know the most proper way
and ignore the techanically okay types
ya, thers a learning curve.. once u crest it.. its all fun and games 🙂
But again, I knew 0 coding in July 2023. And beginner coding in December 2023.
So I guess it plays a huge role too. Building blocks and then connecting them through logic.
Currently, I'm an intermediate or more C++ developer (2nd semester of Bachelor's just ended) but yeah... I wanna be a few steps ahead of my colleagues 😉
humble 💪 flex
would this be the cause for this API change?
only namespace im using is AI (Unity6) project
yeah, probably
alrighty.. just checking bfore i decline it
linearVelocity ftw
yup, that was it ☑️ , was gonna go old school w/ the rigidbody stuff
could always use some preprocessor directives if you want to maintain compatibility with older versions. or you could disable the warning for that line 🤷♂️
i'm fairly sure that velocity still works, it just internally uses linearVelocity
Genuine Question : Why do you use VS Code? 😭
Aren't VS and Rider the most preferred and optimized for Unity?
i use both

That's a relief to know. Because I actually researched on this (didn't wanna leave VSCode) and learned that it is possible to code Unity with extensions and stuff.
So I simply went for VS after that
ya, with the right extensions its still pretty good
That's nice to know 🫡
Question : I have an animation flow like this:
Idle state -> Hold state
When ball is thrown, repeat
But obviously using time to do this is unreliable. And Animation Events are being soooo tricky for the prefab. What do I do to get the same result as I am getting right now?
Animation events or StateMachineBehaviours are the way to go
not sure what you mean by animation events being tricky for a prefab.
if i get a script component from a prefab that contains a bool can i use it in another script?
you can do whatever you'd like, once you understand and are comfortable with dealing with references.
in the second script i used GetComponent but i can't seem to use the bool
from the first script
i can't seem to use the bool
This is very vague
Show your code and any full error messages you're getting.
i'm not getting an error but i'm having trouble with the reference
If you want help you're going to have to show detaiuls of what you're trying and what's going wrong
if you're not getting errors you'll have to explain what you mean by "trouble"
can i just copu and paste
!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.
read the bot message
its backtics you can copy it
(though ideally entire class would be best in a link)
using System.Collections.Generic;
using UnityEngine;
public class ScoreScript : MonoBehaviour
{
public LogicScript logic;
public PlayerScript player;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerScript>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
logic.AddScore();
}
}```
Ok now can you explain what the "trouble" you are having is?
Yes I added an event but you could guide me on this please?
So basically, the event controller is on my character.
But I need different scripts (one on ball and one on balls spawner) to call the animations. And event demands a function from the scripts attached to the same gameObject. So, how exactly can I achieve this?
thank you very much i'm sorry
you put a script on the object with the animator that has the function.
Have that function call a function elsewhere, however you need.
i made a bool for IsAlive in PlayerScript and i want to use it in ScoreScript because when you die you keep getting score
ok so what's the trouble you're having though?
i can't use the bool in ScoreScript
i don't know
what did you try
YOu don't know what happens?
Something is happening that made you come here
- You tried something
- Something bad happened
- You came here
nothing is happening that's the problem
Tell us about 1 and 2
i'm very new to programming
Ooohh yes! ControllerScript on character. That script has reference to other objects/scripts. Then calls their functions. That's a genius idea 😭. Thank you!
have you checked the console window for any errors?
start with that
i don't have any errors
Well, when you write a program, nothing is going to happen until you write code to make it happen
check the code/ function is even running
put Debug.Log inside methods, start debugging
o tried to put if (PlayerScript.IsAlive == true) AddScore();
Ok now we're getting somehwere
this is the 1.
the thing you tried
yes
So this is wrong because you used the class name instead of your actual reference variable
you need to use your reference variable
if (player.IsAlive) AddScore();```
this would give errors 🤔
(unless IsAlive was static somehow..)
i was being hasty my bad
if (PlayerScript.IsAlive == true) { logic.AddScore(); }
that's what i meant to send
i'm very
sorry
This is still the answer #💻┃code-beginner message
OH THANK YOU SO MUCH
And what you have would still give you errors
so when you said you had no errors... that wasn't helpful
i'm stupid
yeah you probably weren't looking at correct spot
i forgot i removed the code when it didn't work
or your IDE is not underlining you have a bigger issue (don't code without configured IDE)
is your code editor doing this when you typed it first time
yes it was there
oh ok well, you saying no errors was misleading lol
moving on.. whats your new question?
i forgot i removed the faulty code
i added a tag to a prefab that makes it so when you touch it you die but the copies of the prefab don't have it
make sure you applied the new changes to all the prefabs
ok i'll check thank you
if you drag a prefab inside the hirerchy it becomes an Instance, anything changed there wont affect other prefabs unless you apply the "overrides"
thank you so much it works
now my game is complete 😎
after i dragged the new prefab into the spawner it always stops after spawning two prefabs
even tho i set the function to spawn a new prefab into void update
maybe this has to do with the fact they all have the same tag?
you'd have to show the code
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class TowerSpawningScript : MonoBehaviour
{
public GameObject tower;
private float time = 0;
public int delay = 3;
public float DistanceOffset = 10;
// Start is called before the first frame update
void Start()
{
SpawnPipe();
}
// Update is called once per frame
void Update()
{
if (time < delay)
{
time += Time.deltaTime;
}
else {
time = 0;
SpawnPipe();
}
}
void SpawnPipe()
{
float LeftMost = transform.position.x - DistanceOffset;
float Rightmost = transform.position.x + DistanceOffset;
Instantiate(tower, new Vector3(Random.Range(LeftMost,Rightmost),transform.position.y,0),transform.rotation);
}
}```
i don't have any errors i double checked and i didn't change any code after it was working
no code that has to do with the spawning at least
Are you looking at your console window?
this is a extremely dumb question but
private void blahblahblah : blah
^^
what's that bit called? if forgot:(
My guess is you are not using a prefab, but rather an object in the scene, and once it gets destroyed your Instantiate code no longer works. When this happens an error will go in the console
& are you spawning a prefab.. or a copy of something in the scene?
a function i think
That line is nonsense. \
once it gets destroyed (off the side of hte screen) or w/e it doesn't have a reference to anything ot copy anymore
have a feeling they dragged in the prefab from the hierarchy
It would either be public class/struct name : something
yes
what's the part
after the function name
The part after a function name doesn't use :
like
function : monobehavior
use the prefab from the Project window, not the one in the scene
no
Functions don't do that
class sorry
you're confusing functions with classes
class : monobehavior
what's the second part called
It's a just a type - a class which blahblahblah is extending, or an interface which blahblahblah is implementing
how
That's the class which your class derives from. It's the parent class of your class.
You can also put interfaces you implement there
oh ok. thanks!
these are prefabs
wdym. just drag and drop it in the slot.
where do you find the project folder i mean
i dragged an asset to the hierarchy then i added some children
and then i dragged it back into the assets i think
and it created a prefab
where do u think ur dragging assets from?
"the bottom"
oh i understand
those tabs have labels
my bad
https://learn.unity.com/pathway/unity-essentials
just gonna leave this here..
why is there a problem if i drag it in from the hierarchy but not if it's from the project folder
because the one in the hirerchy is only an "instance" of the prefab
^ its a copy
a copy
ur copying a copy
but what was happening was.. the copy of the pipes u slotted into the slot.. got destroyed..
and then the script couldnt spawn it anymore
prefabs from within the project folder dont get destroyed.. (jsut their copies do)
show the console window when it stops spawning
it doesn't stop spawning but the tag isn't getting copied
OHH
thats why i told you to apply the tag in the Overrides
maybe i should think more
crash course
Tank -> drag in scene -> now its an instance (if i modify THAT instance) it doesn't matter..
BUT if i APPLY the overloads (now the prefab matches the version i changed)
you can also just double click the prefab.. and it opens in (prefab view)
i changed the prefab itself this time by clicking it in the project folder and the selecting the tag
that will change all versions (even the ones u already have in the scene)
i'll keep all this in mind next time
Any recommendations on an easy to use asset to build out game settings? I need something to read and change settings such a resolution, turning shadows on/off, texture resolution etc. I can do the UI for it, and even saving/loading from a file.
just build your own
If you're willing to do the UI and I/O, you're already tackling the majority of the work :P
should i upgrade c# from 9 to 12? i tried to do some array stuff but it said it isn't avaibled in 9
doing so would require you messing with roslyn and it isn't generally advised because it isn't something that is actually supported by unity
i'm guessing you tried to use the new collection expression syntax, but you should just use the older collection initializer syntax
i tried to set an array with a size of four with
array = [blah, blah, blah, blah]
yes that is the new collection expression syntax
what's the old?
Really? I thought actually changing graphic settings on the fly would be a pain? Is it that simple behind the scenes?
Any good tutorials on this sort of stuff? Like how do I change shadow quality on the fly or change texture resolution etc
each of those options usually only takes one or two lines of code to change
Just look at the docs or forums on how to change that specific thing. Then it's just a matter of setting up sliders or buttons/dropdown menus
Thanks, will give it a try. Just thought there would be some well polished tools out there for something every game probably needs
there are plenty of assets on the asset store that have settings menus built in, you could search for those. but if you want to build the UI yourself, then it's literally just a matter of reading the documentation to find out what line of code you need to run for each setting change
Hi, I'm working on a turn-based strategy game and I am working on a system where the player can bring a battle into focus (they will click on a button and the battle will open in a less interrupted window). For now what I've been doing was that I just disabled all the other tiles that weren't a part of the battle and spawned a fog of war. This was pretty performance heavy (a 1-2 second load in debug). I want to transition to a system where I would load a scene and the battle would only happen in that specific scene (and data would be shared through scriptable objects) and then when the player closes the battle, the original scene would be loaded back in. Imagine a 4X game like civ, scene loading is pretty heavy unless the scene would remain in memory, is this possible?
additive scene loading sounds like something that might help
keep the main scene loaded in memory.. and add/remove the battle scene as needed
hello all, how come these values arent assigned? the second screenshot was taken in game
- !code 👇
- have you confirmed that code is actually running?
- if yes, are you certain you are looking at the correct object and that you have no exceptions in the console?
📃 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.
void Start()
{
FindClosestShip();
radarScanner = GetComponent<RadarScanner>();
shipMovementController = GetComponent<ShipMovementController>();
if (shipMovementController == null)
{
airship = GetComponent<airship>();
}
teamController = GetComponent<TeamController>();
masterGunController = GetComponent<MasterGunController>();
ChooseDestination();
shipMovementController.isEnabled = true;
shipMovementController.hasMoveOrder = true;
}
Thanks, will check it out
ah okay
just copy them str8 from the embed
How do I fix these errors?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrabItems : MonoBehaviour
{
GameObject Cam = gameObject;
// Start is called before the first frame update
void Start()
{
}
void FixedUpdate()
{
var ray = Cam.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit)) {
var objectPos = hit.collider.transform.position;
Debug.Log(ray);
Debug.Log(objectPos);
}
}
}
you reference a gameobject at the top.. soo Cam.main ends up as GameObject.main which dont exist..
you really dont even need that reference..
var ray = Cam.main.ScreenPointToRay(Input.mousePosition); this can become
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Camera.main just grabs the Camera thats tagged as MainCamera
and did you verify Start is running
start by making sure your !IDE is configured. then realize that the example code you were provided that used Camera.main was actually using the static main property on the Camera class and was exactly as it should have been
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
yes, i later added a debug log and it logged properly in the console
then have you confirmed you are actually looking at the correct object
public class GrabItems : MonoBehaviour
{
void FixedUpdate()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit)) {
var objectPos = hit.collider.transform.position;
Debug.Log(ray);
Debug.Log(objectPos);
}
}
}``` @frank flare but get ur IDE configured as well
how do I make sure vs code is configured?
void Start()
{
Debug.Log("ai controls started");
FindClosestShip();
radarScanner = GetComponent<RadarScanner>();
shipMovementController = GetComponent<ShipMovementController>();
if (shipMovementController == null)
{
airship = GetComponent<airship>();
}
teamController = GetComponent<TeamController>();
masterGunController = GetComponent<MasterGunController>();
ChooseDestination();
shipMovementController.isEnabled = true;
shipMovementController.hasMoveOrder = true;
}
yes
if only there were a big ol embed posted by a bot in response to the command i used that has links for configuring vs code
this only proves that Start is being called. have you confirmed there are no exceptions? screenshot the entire console window
there are some errors but i am 100% certain it isn't related to that specific script
i looked through these errors already
if you have absolutely confirmed that none of the many errors you are receiving are in the callstack for this code, then you are likely just looking at the wrong object
but also, fix your errors.
im fairly certain im looking at the right object
"fairly certain" is not "100% certain because you've verified"
ive shift selected all of the objects which have that script and it still looks like this
change the log from Start to this: Debug.Log($"{GetType().Name}.Start has been called on {name} ({GetInstanceID()})", this); and show what it prints, then also click the log to see what it highlights and show the inspector for that object
there is clearly something you aren't showing then. share the entire class using a bin site
ty
of course all of this is public . . .
are you certain nothing else is modifying any of these fields?
certain, but let me double check again
while you check, move that log to the end of the Start method too instead of the beginning
nothing is modifying those fields, i had just changed those to public anyways since i wanted to see if the values were assigned or not
you can serialize a field using the [SerializeField] attribute if you want a non-public field to appear in the inspector
but now that you've moved the log to the end of the Start method, is it still printing?
the log is no longer showing
congrats, one of your dozens of errors is affecting this.
oof
so instead of ignoring your errors you should actually fix them
why is visual studio code visual studio code setup tutorial telling about visual studio plugin while there's visual studio code plugin in front of it?
every day is problems with computer...
did you read what it says tho
because that is the one that is actually required
https://code.visualstudio.com/docs/other/unity
Note: The Visual Studio Code Editor package published by Unity is a legacy package from Unity that is not maintained anymore.
ok
you can also read the convenient text right below the image which you've conveniently cropped from the screenshot
ah, I didn't even see it idk why
I clicked unlock button this should work right?
ok
you can remove the Visual Studio Code Editor package btw
so you dont accidentally select the wrong VSC version in External Tools
why is visual studio editor getting un unlocked when I'm closing the menu?
how?
Hey guys I am not sure if this is the right place to ask but I want to make a AR game using Unity and Vuforia, every tutorial or documents that I read state that I need to check Vuforia in the XR settings. But I don't have that option at all but I have the Vuforia Engine in the Hierarchy.
Unlock it, then remove it
this is highly specific to a plugin
how can we help
probably ask #🥽┃virtual-reality maybe someone knows there
Thanks
Hi! I've just made a grenade throwing animation and I wanted to know, how can I make the grenade instantiate as a child of the hand bone and then make it stop being a child and get speed?
also do send the links to the docs etc..
pretty easy really, just unparent it at the correct time. Use the Animation Event
unremovable
its part of engineering package thats why . You can remove that first then Install Visual Studio Editor if it removes it
yes i see in theory how to do it but i have no idea how to unparent it. which line would allow me to do that?
I removed engineering thing and installed visual studio editor thing
these are small questions you can break down to solve the bigger problem.
eg google
"how to parent/unparent object"
was there anything important in engineering thing?
not really
its just something that unity preinstalls
you dont need everything in it as essential
just Visual Studio Editor package will do
why does referencing gameObject not work?
a field initializer cannot reference a non-static field property.
gameObject is a method(property) basically that returns the GameObject attached to this component
you can do the assignment inside of Start. but also this entire variable is unnecessary
hmm right
I thought it would organize code
gameObject is already short enough to get from the Component you're on , assigning a variable to it is double the work
why is main doing issues?
because GameObject doesn't have a definition for main
you probably are looking for the Camera component not Gameobject
yes
they're different?
very different
Camera is a component, GameObject contains components basically
you can do Camera.main since its static
or if you're super micro optimizing or have no Camera with a Main Camera label, you can just do
[SerializeField] private Camera cam
then link that and use cam.ScreenToWhatever
not necessary though as Camera.main already has its own opimizations (so i've heard)
idk what serializefield does
just makes a private field serialized in the inspector
like when you do public it shows up in the inpsector
you can also do
private Camera cam
Awake()
cam = Camera.main
all unnecessary, just showing you there is options
so I can replace it with that and it does exactly the same thing in action but more optimized?
I can't find the number that changes the animation speed
well you still need to assign it. And mind you we're talking about optimization in the nanos probably unfelt
declaring != assigning
the 3 Dots iirc you can switch it to frame and change the frames per second
or use animator
I guess I don't need to know it for now
nah. ur fine with Camera.main
just make sure you have a camera with "Main Camera" tag for it to work
thank you!
how do I check it?
What am I doing wrong?..
go to your camera's gameobject? check if it says "Main Camera" under the tag
what is this supposed to be doing
this thing by itself isn't doing anything thats why error
what do you want to do with preloadAudioData? if its a function, you're missing ()
ok I set tag to main camera
download the next audio track so that it does not load for a few more seconds after the end of the previous audio track
wdym "download"? this doesn't "download" anything, in fact it doesn't do anything at all, which is the point of the error
this is like if you just wrote a line that was 3; that line doesn't do anything. it's just the number 3 on its own
go up to someone and just say "Apples"
it makes no sense lol
"what about apples? what do you want to do with apples"
I do not know which command to use and yes, I am not good at English, I started trying the first thing that came across
then describe what exactly you are trying to achieve
i cannot read your mind, so i have no way of knowing what you are actually trying to do with this statement
then what is this function for if it doesn't do anything lol
there is no function being invoked here
I am saying you 2 minutes ago...
maybe start by showing us that
I need to load the next audio track so that it does not load for a few more seconds after the end of the previous audio track
what does "download the next audio track" have to do with this
what does the number 3 do if put on a line all by itself?
my translator's mistake
hint: the answer is absolutely nothing. just like accessing a variable without using it in any way or assigning it to anything does literally nothing at all
wait a minute
does not load for a few more seconds after the end of the previous audio track
so like a timer before next track ?
Im confused
this doesn't make anything clearer. what are you actually trying to do with the variable you have accessed on that line with the error
chassisRenderer.materials[0].color = new Color(1,(data.primaryColor%16777216)/(65536*255),(data.primaryColor%65536)/(256*255),(data.primaryColor%256)/(255));
Debug.Log((data.primaryColor%16777216)/(65536*255));
Debug.Log((data.primaryColor%65536)/(256*255));
Debug.Log((data.primaryColor%256)/(255));
I have this piece of code, the debugs are 1,0,0 so the material should be red, but for some reasons it appear yellow, can someone help me?
you are doing integer division
mb, it's RGBA not ARGB
I will have 5 audio tracks here, and I need the next one to start in just a second when the previous track ends. But as practice shows, if you do not load long sounds in advance, they will load only after 15 seconds
wtf do you mean by "download" in this context? because that is surely not the correct term
not download, load
any sound must be loaded before it can be played
at this point i give up attempting to help you. you are not making your actual intentions clear and i don't feel like asking repeating questions for the next half hour
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrabItems : MonoBehaviour
{
Camera cam;
void Awake()
{
cam = Camera.main;
}
void FixedUpdate()
{
var ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit)) {
var Object = hit.collider.transform;
Debug.Log(ray);
Debug.Log(Object);
}
}
}
how can I make
var ray = cam.ScreenPointToRay(Input.mousePosition);
always be center of the screen?
at that point you don't need to be using ScreenPointToRay at all, just raycast from the camera's position in its forward direction
like it has Input.mousePosition
how?
look at the documentation for Physics.Raycast
create a new Ray with the desired directions
then in the origin and direction you put the camera's position and forward
^ camera.transform.forward
are you talking about a timer of sorts between switching tracks? Im still confused on what you're asking
not really, I'm talking about the fact that music in unity can't load instantly, personally it took me a few seconds. Imagine, you decided to create an AudioSource and put a certain AudioClip there
I'm trying to do like that
thats now how you create a new ray
var ray = new Ray (cam.transform.position, cam.transform.forward)
and when you log into the game, the music just won't start playing at the same second, because it won't have time to load before that @rich adder
y is the coner tile not auto tiling correctly when i have it setup in the auto tiler
if there specific kind of loop that takes lots of code and i want to use it many times is there some kind of function to shortcut it
I feel like this is an obvious yes, but I don't want to go insane. It shouldn't matter where I put my start and end rooms on a maze generated with a Recursive back tracker right? There should always be one path connecting both?
are you saying there is some type of loading time you're experiencing between clips? not sure I understand the problem tbh
maybe think it over a bit , and try to come up something a bit more easy to explain to someone else what you want
if you cannot explain it, you wont be able to solve it
Yeah, that's what I'm talking about.
in my other game, I just can't load the AudioClip I need because I'm constantly changing them..
I have not experimented with audio that deep but looks promising
write a method with a loop? Not sure what you're asking exactly "lots of code"
Yes, I read a short article about it, but it seemed to me that this was not what I needed.
I'm not sure then :\ sory
works
I think that's what is need
no
this
i have multiple functions with same large loops that do just 1 task
if (MusicsTable[i + 1] != null)
{
MusicsTable[i + 1].LoadAudioData();
}```
i want bind loop into function/interface/whatever thats already preparing it to use
and the loop supposed to do what exactly ?
can you actually describe what you are actually attempting to accomplish for once instead of trying to describe some half thought out way to accomplish whatever it is
btw this returns a bool, might want to do extra verifications
https://docs.unity3d.com/ScriptReference/AudioClip.LoadAudioData.html
bool Returns true if loading succeeded.
loop without 20 lines of preparation
what the fuck do you mean by "20 lines of preparation"
loops are like 3 lines what does that mean lmao
for (int i = 0; i < total; i++) {
one line prep!
not when i put loop inside loop inside loop
and toss variables around
i want to shortcut it
i mean, it's anuked, they probably have 6 lines where they convert all of their data to strings, another 10 lines parsing that data, then 4 lines for the actual logic
can you give like a real life scenario or like your current scenario so I know wtf you're talking about
though when i think of that i probably could do custom class where i already did that loop beforehand toss all variables there and then foreach it in every function i need
or just write a method that does what you need and call the method while passing whatever data you need into it. but until you provide a real example of what you are trying to solve all anyone could possibly provide is speculation at best
ok so for example
car has multiple of parts which each can hold multiple modules
and i want to add same variable to all of the modules at once
while skipping the looping part
Use an event
why, depending on where I'm looking, the grenade never goes off in the same way ?
public void ThrowGrenade()
{
GrenadeInstance.transform.SetParent(null);
Rigidbody rb = GrenadeInstance.GetComponent<Rigidbody>();
if (rb != null)
{
rb.isKinematic = false;
Vector3 localForward = RightHand.forward;
Vector3 localRight = RightHand.right;
Quaternion throwRotation = Quaternion.Euler(throwAngles);
Vector3 throwDirection = throwRotation * localForward;
rb.AddForce(throwDirection * ThrowPower, ForceMode.VelocityChange);
}
}
also if I remove throwRotation the grenade it's not going straight but at least it always go in the same direction
assuming its probably colliding with the player collider
could also be the wrong directon/rotation.
Debug them Gizmos class will be your best friend
I don't put a collider
what's Gizmos class ?
seems like your first throw is also off
so assume you're calculating direction/rotations wrong
how do i change his hands pivot location
yes all my throws are broke
did you switch it from Center mode first of all
the sprite editor lets you edit the pivots, otherwise use a sperate gameobject parent
i would use the direction the player is looking rather than the hand, which is moving via animation
why ?
how?
because you want it to throw based on the direction the player is looking + some offset. syncing it up to throw with the hands local directions is just gonna be more of a pain, although i dont see anything super wrong with the current code. Maybe throwAngles is wrong or this code is playing at different points in the animation causing it to read different values
try to visualize even with Debug.DrawRay to see what these directions are
I use the direction the player is looking and I don't even need offset, It's working perfectly fine ! Thanks a lot for your help !
top left you will see it
I just have a last question, how can I add a collider to my grenade without it interfering with my player's colliders? do i have do disable the collider of the grenade as long as the player holds it ?
everything works thanks
im making a 2.5d game in unity any tips?
is it your first game ?
no but its my first game i actual plan to finish in 3d unity
wait a second it doenst work
it wasnt a "fix"
did you switch it from Center to Pivot, what does it look like now
if this isn't your first game, it should do the trick, even if it's likely to be rather complicated.
just to see where the pivot actually was
sprite render
wat
where do i view pivot
Screenshot the Scene
see how it says "Center"
layer based collisions or set it in the physics.IgnoreCollision
click it, and switch it to Pivot
if its still wrong, after that use the Sprite Editor to edit the pivot
thats great thanks but man it looks complicated
I am making an enimy trying to just follow me, but it just falls straight through the ground
It depends, if you have a good command of 3D modeling software like blender, doing 2.5D shouldn't be so hard.
you have to provide more info on the actual setup
we only know the problem for now, not the cause
ok
i didnt touch blender since episode one of donut tutorial
ah it's gonna be painfull to make 2.5D then
its a pixel game so im kindof good with blockbench
not really. made one without knowing anything about 3D modeling
but where do you find your're asset ?! it's already super hard to have a coherent graphic charter by finding assets right and left in normal times, so in 2.5D how is it possible to have a coherent look without modeling anything?
2.5D mostly you're using simple 3D shapes with 2D sprites as texture
if anything finding similar 2D assets is harder than cohesive 3D
isn't 2.5D game, 3D game where you're only playing on 2 axis like 2D game ?
depends on the game you can also use depth
I always equate it with "Isometric," which may or may not be accurate. But isometric games often incorporate height
Edit: further research says this is not accurate 😁
Like... the camera is not axis aligned to your 2D viewindow?
mostly its having sprites in a 3D world
billboarding and such
but yeah if it moves like 2D (eg side scroller ) helps sell the "feel"
2d sprites in a 3d enviroment
Like paper mario?
yes
or zelda remake
actually thats all 3D models iirc
its just that view thats 2Dish so doesn't count ig
but yeah paper mario is the best example of 2.5d
Ok then yes, even if you're not familliar with 3d modeling it won't be that hard
My friend says that this is right way of making values..
And its right to place [SerealizeField] in public values.. is it so or he's just dumb?
no you dont need SerializeField a public as its already serialized
Hence the 3 dots on it suggestions from VS
if these are not accessed else where make them [SerializeField] private
thats what its fore
name checks out
thanks
wdym?
language barrier?
more like zero modelling experience.. no need to even open a 3d program to do sprites in 3d / 2.5d billboarding
billboarding?
sprite of garfield.. -> ur name is garfield
thats what its called when a sprite in a 3d environment
tree's in the background for example
*always faces the camera
lol ya my friends said the main character should be garfield
like how some stuff in baldis basics look weird
hell ya, trying for that cease and desist achievement ⭐
actually all of baldis enviroment is strange
You have unlocked LAWSUIT
a wild trademark attorney has appeared **
just kidden, as long as u dont redestribute it outside ur friend circle u should be ok
not legal advice
movie companies are ruthless
my only cease and desist came from Fox
i will call him gaafar and change a bit of his looks and he is an arab cat with an atayef addiction
futurama asset? lol
family guy
there are garfield fangames that are horrifying
as long as you're not selling it should be ok (not legal advice)
alright
thanks for the advice guys
heck ya, gotta throw up that disclaimer.. i do it too 🤣
ahhh heck ignore that, i cant share those lol
i have a cylinder and cube one on top of another. Both are instanciated prefabs. if i click on the cilinder it says its pos is 4,0,4. If i click on the cube it says its -540,0,4. yet both have the same size? How is this possible?
they can be teh same size and @ different locations?
are they children of anything?
but they are one on top of another
The position displayed in the inspector is relative to it's parent... maybe they have different parents?
oh they are
thanks for the clarification
hey! i have a canvas which is a prefab which is a worldspace canvas, but the buttons don't work and none of the keys i press trigger the coresponding stuf, any idea why?
no idea why, you havent posted the code or anything
everything else is just throwing darts at a board
Do you have an EventSystem in your scene? 🎯
well there isn't much code, it's just that the canvas doesn't seem to be updating at all
i have one in the prefab
so you are trying to interact with world canvas how exactly? fpv or wat
also ur in a code channel 😛
shit sorry!
i have a peice of code that runs every frame
that checks if "W" is down
and if it is
change a variable
but w isn't triggering
how did you check the code is running ?
because when during awake() it prints "started" and it printed that
it works when not a worldspace, only breaks when it is worldspace
are you using a FPV controller ?
what's that again? sorry
it's just the w key
like clicking "w"
then yes
thats probably why
your cursor is locked and not visible most likely
world canvas doesn't like that
ah alr
try using this module instead
https://gist.github.com/navarone77/4addc1f6486a851b4d6994a2a9bd6d04
replace the one on the Event System
do you have an event system object in your setup? if so can you screenshot the gameobject
new
use that method instead then
hopefully that works, I havent tried new input system yet with this
Where does GetComponent()'s overhead come from?
Is it just managed/unmanaged interop shtuff? Outside of that, all I can conceive the components collection to be is just something like a type-keyed dictionary, and lookups there should be cheap, no? 🤔
I don't think it's a map/dictitionary, since you can have multiple components of the same type. It could be a map of vectors(the c++ dictionary and list), but I think it's just a vector(list) of components, so it needs to loop all the components to find the right one.
Either way, without access to the source code, it's all speculation.
Also GetComponent is not that slow.
yes TIL GetComponent is quite fast
was watching a performance test video and several things people think are better turned out to be slower, example FindBy Tag() was fast
Sure sure... I had just recently written a method with a similar signature and purpose, and it got me thinking.
I appreciate your speculation though - that all seems reasonable 👍
public class PartBase : MonoBehaviour
{
public float maxHealth = 100;
public bool interactable = false;
private Vector3 originalPosition;
private Rigidbody originalConnectedRb;
private FixedJoint joint;
private bool wasActivatedBefore;
private Rigidbody rb;
protected float health;
protected bool isActive = false;
void Start()
{
rb = GetComponent<Rigidbody>();
TryGetComponent<FixedJoint>(out joint);
Reset();
}
public void Activate(){
isActive = true;
rb.isKinematic = false;
originalPosition = transform.localPosition;
if (joint) originalConnectedRb = joint.connectedBody;
wasActivatedBefore = true;
}
public void Reset(){
isActive = false;
rb.isKinematic = true;
if (wasActivatedBefore){
transform.localPosition = originalPosition;
if (joint) joint.connectedBody = originalConnectedRb;
health = maxHealth;
}
}
public void DealDamage(float damage){
health -= damage;
}
}```
there is a rigidbody yet it says the `rb.isKinematic = true` line throws a null exception
Does anything external call Reset()?
yes
a thing calls a thing that calls reset
oh no
they all call each other in start
is that it?
Quite possibly.
A common practice to have a script initialize itself in Awake() (cache references to it's own components and such), and anything requiring interaction with other objects/scripts happens in Start()
it is 
alr i will do that from now on thank you very much
For object pooling is it better to store objects in a list or an queue?
THat would be situationally dependant on how you are going to use the objects in the pool
when u find out let me know
i use a Queue for my frame rate counter
(keeping a list of the last few seconds to average them into a rolling value)
but, i've also had that question.. would a list be better?
i dont think i can test w/ the accuracy to know which ones better
Also are you talking about the actual pool? And if so, are you rolling your own or using Unity's. If Unity's you don't care how the objects are stored in the pool. If rolling your own that's a tough one. But once you get them out of the pool what you store them in is going to depend more on how they will be used from there.


