#💻┃code-beginner
1 messages · Page 49 of 1
What course is it?
Yeah. I know it is wrong sometimes.
Check the comments for that part
People often give explanations there
It also has super weird picky specifications sometimes
Like one answer is right, but not the one they want
i wish i could skip all this easy stuff cause i already do it a bunch
yeah
if you know any other places i could learn id switch over...
There are pins in this channel.
Other than that, I liked https://www.w3schools.com/cs/index.php
There is also https://www.tutorialspoint.com/csharp/index.htm
can someone help me with:
I want the player(ball) to rotate right when its moving towards right and
rotate left when its moving left
is it possible to combine a transform.up with a euler angle rotation?
You can rotate a rigidbody by applying torque to it. Also I'd recommend not using translate with rigidbodies.
Not sure what you mean by "combine"? If you mean adding them up, then no, one is a direction vector and the other is Euler angles.
my problem is that setting the transform.up resets the transform to the default world axis
I want to maintain a look direction while also changing the transforms rotation
Setting a look direction is 2/3s of setting the rotation
You can use Quaternion.LookRotation to create a rotation with a given look direction+ an "up" direction to determine the roll
if (transform.eulerAngles.x == 180 || transform.eulerAngles.z == 180)
{
transform.rotation *= Quaternion.Euler(0, -prevLookDirection, 0);
}
else
{
transform.rotation *= Quaternion.Euler(0, prevLookDirection, 0);
}```This is what I've got rn
Yeah don't do that
ignore the if statement
Euler angles are usually the worst way to do things
You want to look a certain way and align to a surface normal?
Use Vector3.ProjectOnPlane to project your look direction on the surface.
Then use that result with Quaternion.LookRotation and the surface normal again as the up param
That kind of worked
Only problems are now each time I change surfaces I get turned to look directly at the surface, also being completely upside down doesn’t work
Is being upside down something you need to do?
You haven't really explained what you're trying to accomplish
Hi, imagine this is a bit of a stupid question, but my UI button won't click. When i click it it selects the items behind it. I did set the right sorting order but still the same.
Do you have an event system in the scene?
Not sure what you mean by select other things. Is that ui stuff too, or a raycast or what?
No, i don't. This is all in the editor itself. I tried to click the ui button, but instead it selects the other elements in Hierarchy
Ok.
1, you need an event system
2, if things in the hierarchy are being selected then you are in the scene view? Did you try in the game view?
Do you mean you just want to SELECT the button OBJECT?
Maybe I was misunderstanding
I mean select in the editor, not in game. I just can't select the ui button in the editor.
So like I add a UI button and I want to move it aroud, but i can't, it won't let me select it, it selects other things in the hierarchy
when using rb2d AddForce, does it matter if i put it in fixedupdate or regularupdate?
Ok.... looks like you could just select it via the hierarchy though? Since you send the screenshot
Then you can move it via the inspector
Yes, i can select it via the hierachy, but i'm confused as to why i can't select it visually?
Do it in fixed update
All physics in FixedUpdate
I put the ui buttons in here:
Can you show the whole editor instead of cropping it? Also have the thing being selected other than the button in the inspector
Cropped images are usually not very helpful
Wait.. so all the objects are in the exact same position?
The three buttons under the canvas I mean?
Under Main?
They both at least have the same z position
No, they're next to each other.
Ah ok, same y but very different x
yes 🙂
This is the issue i'm dealing with
So... yeah. That is weird. I assumed they were blocking each other from the beginning, but they aren't even overlapping...
Try using a different tool
Different tool?
In the top left of the scene window is a column of tools
Click the hand, or transform tool
The hand tool is to move the scene around, the transform tool is to resize, i can't do that without selecting the ui buttons first.
Your right about the hand tool. I meant translate tool. The one you're on is not the right one is all I meant
Did you try the others?
Not sure why those two don't work, but you should always capture input in Update, not FixedUpdate. AddForce is in the right place though
how do i capture input in update and the addforce in fixedupdate? they have to be in an if statement in the same function no?
you can addforce in update
They do not. You can cache the input as a vector. But I guess you can do it on Update. AddForce isn't the worst one to do in Update
It is certainly BETTER in Fixed (especially in forcemode as a constant, as you have it)
my mistake,only a & d work
Yea, still the same, i can grab and move all other sprites and elements, but the ui buttons nothing, is this normal?
No. I am clicking on my UI right now.
I just tested and all tools except the hand can select them.
Only thing I can think is that you need the event system? Shouldn't need it for just selecting in the editor... but may as well try
Even ui buttons?
Yep
I do have an event system in my hierarchy
Yeah, too much to hope for. I have no idea, sorry
Are you sure about this? I mean... Impulse mode sure, but for constant addforce as the main movement... it just seems not right
Everything I see says no. And I have personally had issues with that in the past
yes, only instant velocity change can be applied in update....
~~Ok... and AddForce is calculated velocity change. Even the docs have it in FixedUpdate
This is rigidbody movement, which belongs in FixedUpdate.
Impulse mode is the only one that makes sense in Update~~
~~Using AddForce as the main movement (applied every cycle) absolutely should go in FixedUpdate
It of course CAN go in Update. It just SHOULD not~~
I think I misunderstood your response
if the change is derived by dt then it should be handled in fixed update though i think you still can simulate it update
Eh? Dunno what is happening here
Debug.Log("2: " + characterHealthRegenPercentage);
Debug.Log("3: " + (character.MaxHealth / 100 * characterHealthRegenPercentage));```
how is 40 / 100 * 10 = 0?
is this some sort of int/float conversion issue?
Yes
(float)character.MaxHealth / 100 * (float)characterHealthRegenPercentage)
yeah this actually works
how do I prevent this? what's the proper workaround?
you convert it to float before multiplying, that's all
I'm not sure which ones are ints or floats, but casting (putting (float) behind a value) is a proper workaround.
they're all ints, even the result needs to be an int lol
I have a Mathf.FloorToInt in the actual calculation
int regen = Mathf.FloorToInt((float)character.MaxHealth / 100 * characterHealthRegenPercentage);
If this is working as intended, then you've done everything right.
Back to this for a sec. It seems like I can't press buttons in game either.
the logic behind it is just crazy confusing, well it makes sense
but this will probably cause some more issues in the future
When working with ints you always need to make the consideration of when you will use it for math. If ints are too problematic, which they never should be, you can always change it to a float. I think the way you have it is the simplest solution.
Okay, seems like I needed to add Raycaster to the parent for some reason to finally click on buttons
disabling raycast makes objects not-interactable - I don't know anything about this, just saw it in a tutorial
I'd just make health a float and round it up after adding any modifying operations to prevent truncating too many values.
@topaz mortar Why dont you simply do
(character.MaxHealth * characterHealthRegenPercentage) / 100;
!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 if that causes the number to go too high before it's divided by 100 (out of int range)
wouldn't that cause the same issue?
alr, it making Near tag true, but why it doesnt make tag false when character is away?
https://hatebin.com/eqqatzjckn
int out of range is very large indeed, unlikely you would reach it
probably
Firstly, OnTriggerEnter only runs when you enter the trigger. It doesn't run again when you exit the trigger. There's an aptly named OnTriggerExit for that. Secondly, the logic is wrong: it sets the near flag false if something that isn't a player enters the trigger
ok, thanks
private void LateUpdate()
{
lifebarCanvas.LookAt(this.transform.position + Camera.main.transform.forward);
}
I am using a simple lookat function to let my hp bar look at the camera in the late update. However, I find that the hp bar become kind of "broken" (red arrow) when the enemy is moving. How can I fix it?
Try sticking it in update
how do i animate a line renderer? i want it to wobble as it moves like its coming out of a grappling gun
Tried in update. It become worse as the hp bar is shaking when enemy is moving
Instead of having a different canvas you can try having this panel in overlay canvas and in update set the position of the healthbar above the player
That way it will always face the camera and no need to implement look at
the healthbar is above enemy not player, and the health bar is supposed to spawn along with the enemy
In that case set the position of healthbar above the enemy* I'm not sure how a seperate overlay canvas looks for each gameobjects but it should still work if you change parent of healthbar to the main overlay canvas...anyway I think I remember seeing a codemonkey tutorial for this issue
I have searched tutorial before but he's in 2D
I do most* billboarding stuff through vertex shaders and using screen position over using camera position
overlay canvas sounds like a nice alternative
I am trying right now
https://youtu.be/6U_OZkFtyxY?si=h9e-Ltd6ovyX0QGN
This one for 3D
Create a healthbar for your player character in Unity. Bonus: I'll show you how to smoothly animate the remaining health to give it some cool points!
p.s Sorry about the crappy audio on this one!
❤️ Become a Tarobro on Patreon: https://www.patreon.com/tarodev
=========
🔔 SUBSCRIBE: https://bit.ly/3eqG1Z6
🗨️ DISCORD: https://discord.gg/tarode...
is it possible to get gameobject -> component from another scene? this really annoyed me for the past few day since i started unity
You can make the gameobject a prefab and instantiate it on another scene, or if you previously were on that scene you'd use don't destroy on load when loading the new scene to carry it over.
Are you asking via script or in just editor?
script
you can save data on computer and when scene loaded it will load data from computer (lot of code)
trying to access gameobject script from that "current scene" scene
Could someone help me with the scrollview thing? It returns to original position and the contents inside even go out of bounds
whats wrong i dont understand
if (Input.GetKeyDown(KeyCode.E) && inShop == false && near)
{
inShop = true;
}
when i put only Input.GetKeyDown(KeyCode.E) it works, but when i add bools it doesnt work
Object reference is null
log what you're accessing
this is not my script, its unity
ah.. didn't know you can use prefab into another scene, this is new
Oh, huh. Sounds like a googling, maybe even try restarting the editor.
it worked, but after some time it just stop, yeah ill try
nothing changed
great, when i removed bools it doesnt even work
Only other thing I can think of is you were working on some asset and deleted it, but the editor is continuing trying to access it
i think i know how to fix it
fixed
i put code on line 37 (it was on line 21) and it fixed somehow
im sorry but is this the right way to do it, i tried only using 1 audio source, ofc it doesn't work 
AHAHAHAH, I DOESNT WORK AGAIN
How about sending the entire code
i dont know why, but upper "if" is not working
https://hatebin.com/pwsehmdeya
when i replace them, they are working
Why can't i move a panel with in a scrollview?
What's the error you're getting right now with this code? And on which line
it works, but i like to use a class called Sound which has all the properties of an audioSource, then in an AudioManager script having an array of Sounds and having them be accessible in the inspector. then later in the AudioManager script it adds an AudioSource for each Sound in the Sound[]. its exactly the same thing as your doing it just makes it a little easier on the eye when not in play mode
im not getting error, in blue part of code you can see what when i press E it enable shop, but if i press it again it disables, but upper IF doesnt work, if i place upper E down, it will work but another one will not work , its like something always blocking it
thanks, thought im doing it wrong ("i am")
wait, why are you even doing it separately in the first place?
wut?
Hm, I have a question
https://gdl.space/ijapalosur.cpp
I want too make the selected unit move to a location that I click, but I am not sure how I should do that, here are the scripts I have so far-
instead of checking if inShop is true or false, just switch these things within the other two if's
if (Input.GetKeyDown(KeyCode.E) && inShop == true)
{
inShop = false;
baarenController.blocked = false;
controlls.needed = false;
}
if (Input.GetKeyDown(KeyCode.E) && inShop == false && near)
{
inShop = true;
baarenController.blocked = true;
controlls.needed = true;
}
Idk why separate it
It's pretty simple actually. Code runs from top to bottom. When you set inShop to true in the first if statement, then the second if statement always run since you just set inShop to true
So you need to use else if
Ah, that's also true ^
ill try
Could someone help me? I'm not able to move the contents inside content. I can neither resize or remove them, it's like they're anchord.
Maybe you have some script attached which moves and resizes them
finaly worked, thanks
quick question about saving large amounts of data
do you have one script that iterates through every script and saves everything and when loading every script gets through functions their data back or does every script save for themselves`?
Probably some script preventing it. I believe the scroll view instantiation comes with a collection of gameobjects.
Yes, the grid was causing the issue, i fixed it 🙂
For now the scrollview is somehow white
If you got dependencies for saved data which also requires deserialization, you'd eventually want an ordering to it all.
hm im not a native speaker what do you mean?
you mean if i have an order in what the data should be loaded or saved i should use one big script?
Meaning that having everything load itself independently may not load data correctly. If for example you've weapons that have modifiers that have be serialized, well you want to load those first before the actual weapons and such.
ok so One big script and this script spreads the data to every script?
Is it possible to the background colour of a scroll view and have the background simply be a photo?
I'd a fan of a general load manager, with smaller sub load/save systems
load manager?
Somehow the scrollview is looking white like this, how do i remove that entirely? because the white is supposed to be a sprite background
Yes, something that executes the bulk of the serialize data first like location, events that been triggered, then load lesser data like inventory.
But each would be a subsystem too, for example with the weapons again, you need the logic to recreate these specific weapons with the modifiers it had previously.
If the game updates like i pick up one wood, should i send this data to the save script and if i press save it saves or when i press save the save script should pick the data that i have one wood out of the inventory script?
Hey my friends, how do i create a simple logic to make a game object always go in the direction of another object no matter where the other object goes? like if its an enemy that always go towards the player? tried something like that but it goes to the position the player is just first time and stop.. even in start method. Vector3 direction = _player.transform.position - transform.position; transform.Translate(direction * _speed * Time.deltaTime);
Does anyone perhaps know how to remove the white background of a scrollview?
Depends how frequently you want to serialize that data. Older games you've probably played only saved at points, but arguably that was also part of the difficulty of the game. But nowadays you can pretty much serialize data for every little action you do in case a player's game does crash. But, to keep it simple for now, I'd suggest just serialize the data when the player prompts, or perhaps write the data in increments between scenes, ect.
Save button
Start method executes only once, and your direction vector should be probably normalized, since as it is right now it's just a vector which spans from your enemy all the way towards the player and using Translate like that will get you there in 1 / _speed seconds
oh SORRY it is in update .. i said it wrong
Either way, read the rest
maybe make the Alpha to 0...
so uh- any tips on how to do this?
Raycasts for the position, direction for your unit, velocity for the movement
ideally you'd want to look into unity's pathfinding
Raycast?
will check .. thank you
thank you a well
What is the purpose of having these items in brackets like this?
if ((Object)(object)m_lastAttachBody != (Object)(object)m_lastGroundBody)
hello guys how can I make my enemy prefab get the right gameobject to follow like when it spawns the gameobject it should follow is missing from the checkbox
The object in your prefab is probably referencing an asset and not a game object in the scene. Whatever spawns the enemy should tell it what to follow and you should cache that game object to follow in the spawner
hey guys if I use 2 dots like that, what that means? var target : Transform;
It means that you're looking at old forum posts or tutorials that use Unityscript instead of C#
ty
The only thing I can think of that uses : is a switch and case
As a beginner things takes like hours just to learn how to move 1 thing or etc.. but i will be resilient hahaha
can I not declare the gameobject in the start function?
How are you doing th code?
imma send the chase code one sec
public class AIChase : MonoBehaviour
{
public GameObject car;
public float speed;
private float distance;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
distance = Vector2.Distance(transform.position, car.transform.position);
Vector2 direction = car.transform.position - transform.position;
direction.Normalize();
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.position = Vector2.MoveTowards(this.transform.position, car.transform.position, speed * Time.deltaTime);
transform.rotation = Quaternion.Euler(Vector3.forward * angle);
}
}
its from yt but I want to update it with more things that my game needs
the player
oh it seems more people want to do the same as me now 😛 hahaha amazing
they just spawn at the spawner locations
So the spawners should on awake figure out what the player means, like find the player based off of a tag and store that as a variable
and then when a spawner spawns an enemy it should do like SpawnThing(player)
ye but like the spawner only spawns them it doesn't hold any variable of the enemies cause it has an array that randomly chooses which one to spawn
or you probably do this
void SpawnEnemy() {
var enemy = Instantiate(EnemyPrefab);
enemy.player = player;
}
lemme show u the spawner code too
public class EnemySpawner : MonoBehaviour
{
[SerializeField] private float spawnRate = 1f;
[SerializeField] private GameObject[] enemyPrefabs;
[SerializeField] private bool canSpawn = true;
private void Start()
{
StartCoroutine(Spawner());
}
private IEnumerator Spawner()
{
WaitForSeconds wait = new WaitForSeconds(spawnRate);
while (true)
{
yield return wait;
int rand = Random.Range(0, enemyPrefabs.Length);
GameObject enemyToSpawn = enemyPrefabs[rand];
Instantiate(enemyToSpawn, transform.position, Quaternion.identity);
}
}
}
It doesn't matter how the code is, it needs to pass it the player variable or you need to find the player by tag on each newly spawned enemy which is worse for performance
if you had a GameManager you could store these kinds of variables there to be instantly accessable by any script during runtime
var spawnedEnemy = Instantiate(enemyToSpawn, transform.position, Quaternion.identity);
spawnedEnemy.player = player;
Like I said, it doesn't matter
Usually you make an Init() method inside of classes that are designed to be spawned
And you access that after spawning and pass all the variables and it functions identical to a Start() method
ight thanks imma try to do what u said
It won't work as is obviously, you'll have to fill the gaps
those 2 simple lines should work no? at least logically. I am saying translate to the position of the played in a specific speed but nothing happens.
The player's position is not a direction. It's a position.
directions are positions, they are just normalized
hmm.. hard to understand hahaha.. if I say translate to 1, 1, 1 and I am at 5, 5, 5 he shoud do the math and go to 1, 1, 1 that is what is in my head but it seems it doesnt work like that
you should inscrease the speed a bunch and see if something happens
tried nothing happens
No, the Translate method moves it towards a direction. Not towards another position.
Can anyone point me towards a yaml reader? Importer? Iunno.
I don't have/can't have a object made so.
but that is not there already inside the variable direction ?
Direction would be (_player.transform.position - transform.position).normalized
no it would not
ok then
just p(i)=p(i-1)+p(i-1)*dt=(1+dt)*p(i-1) i=iteration here
so p(i)=(1+dt)^i*p(0)
yo but can't I do in the ai chase script an awake method and in there say
car = and find the tag of the car player
wouldn't this be better and easier?
okay I read it now you can add the transform.forward to the variable
should fix it
Like that? Vector3.forward direction = _player.transform.position;
How is it that I can scroll out of bounds with the scroll view?
No, that means every enemy looks for the player rather than every spawner tells the enemy what the player is
no
Vector3 direction = _player.transform.forward;
Vector3 direction = _player.transform.position + _player.transform.forward;
You really have to do some basic tutorials to learn the syntax. As a bonus they also show how to move things around.
Could someone help me with scrollview? As you can see I scrolled up and it shows up out of the bound, i want it to remain inside all times.
its uneffective but its easier for me to understand and do myself at my level of knowledge
just completed a 40h unity course but its not easy hahaha ty tho 😄
People learn at different speeds and have different backgrounds, nothing that can be done about it
oh i misread
p(i)=_player*dt+p(i-1) so p(i)=_playerdti+p(0)
and direction vector is (end point-start point).normalized btw
Do what ever you want if it works. You'll learn why I told you to do it the other way one day but for your purposes I'm sure it's not useful
thanks I am new so I don't have that knowledge yet I only can code in c++ from school and c# is not a lot more different but unitys different functions and stuff is hard to get atm for me
btw its working as I want to
like that is working but it moves only one time and stops even being in update
I'm not sure why it would do that unless you disabled or destroyed the script, but you should normalize direction before you use it
This is a programming channel. 👉 #archived-pricing-updates-talk
A bit late to the party ngl.
wrap the right hand side of the direction with .normalized
does anyone know if a mesh collider on something like this wedge would be horribly expensive?
Profile it and find out. And as I just said, this is a programming channel.
tried to watch some youtube videos.. each one people do it dif.. and some use even rigid body for that.. hahaha i just stay every time more confusing.. that looks something that might be so easy to do hahaha.. i am so f. dumb
I asked chatGPT and he gave me the same thing i did before but doesnt work.. hahaha.. chat GPT is dumber than me
even tho it moves to the player but to the first position .. its like it is not inside update checking every frame and chaging it..
If it moves correctly to one position then the only explanation there is that the target is not the player but some other object in that location
there is just 2 objects in the scene.. player and enemy and I have the player there in the enemy so i can access it from the enemy script
I'm guessing that when the player moves you're not moving the main Player object but a child object inside it
the main camera is inside the player and the script that i use to move is inside the player
So this script is on the camera?
no on the player
I am trying to make the scene and script as simple as possible but even tho as simple as it looks doesnt work hahaha.
What does SpawnManager do?
Does the player move at all on start?
nothing yes just created an empty SpawnManager
as I thought that would be easy to move the enemy to the player and than i would create the spawn system
i know how to create the spawn system but i am stuck to the first part hahaha
that is move the enemy to the player hahaha
Its moving to origin because you are not adding it's postilion in the translate
transform.Translate(MoveDirection * _speed * Time.deltaTime); in this line?
No, that's fine. Show the same video but have the player object visible in the inspector
Try adding Space.relative after delat time inside the brackets
transform.Translate(MoveDirection * _speed * Time.deltaTime, Space.Self);
although it does that by default
it doesnt allow me
This looks fine.
I think I know what it is
is the player ref becoming null on runtime?
actually, you want the opposite
Space.World
You've dragged the player prefab to the target field, not the player object in the scene
Aha. That would do it.
space.world same result
The default behavior of transform.Translate is to move you in local space
In this case, it doesn't matter, because the enemy is not rotated
If the enemy was rotated, it would matter.
oh its not the prefab i need to drag? hmm ok let me try
but yes, this is your problem.
well, of course not -- the enemy needs to chase the player in the scene
thank you everyone you guys are awsome
It was looking at the prefab which doesn't move
Unity won't turn that prefab reference into a reference to the specific instance of the prefab
You should definitely add Space.World while you're fixing things, though
If the enemy is ever rotated, then its local directions will no longer match the world's directions
So if it wants to move to the right, but it's rotated 90 degrees, it'll move vertically instead
got it thank you
I would normally just do transform.position += ... to directly move an object in a world-space direction
transform.position += foo;
transform.Translate(foo, Space.World);
these are equivalent
hmm ohh nice ok got it.. thank you
You know, one thing I don't know is whether transform.Translate takes scale into account
I don't think it needs to
Good question, docs don't really say much about scaling
I doubt it scales the position
My bet is on not-scaling too
Oh right, even transform.localPosition += foo wouldn't care about the transform's scale
I was thinking about it all the wrong way
The more interesting thing would be how parent scale affects it
Space.World is just a shorthand to position +=
https://github.com/Unity-Technologies/UnityCsReference/blob/c0058685e1f312abb957997394e413664948b00d/Runtime/Transform/ScriptBindings/Transform.bindings.cs#L122-L128
Space.Self uses some internal method
but I can't imagine scaling would affect it differently depending on space
If your parent is scaled to 10x, transform.Translate(Vector3.forward) changes your local Z by 0.1
I was wondering if these were equivalent
transform.localPosition += foo;
transform.Translate(foo);
the anwer: no!
Now I have another question.. If I apply the changes now to my enemy prefab.. and i drag a new enemy into the hierarchy, it doesnt have the player there anymore.
Right.
That's a scene object reference.
Prefabs can't reference scene objects.
what if the prefab was created in a different scene?
hmm.. so how to fix that when i want to spawn enemies ?
You will need to do something to tell the enemy about the player
One easy option: have the enemy find an object of type Player
oh ok.. like refering it inside the code and not using the inspector
ok got it
will try
player = FindObjectOfType<Player>();
Another is to put an enemy spawner in the scene
and then have the spawner reference the player
then the spawner can tell the enemies it spawns about the player
If you do this, you should do it in Start.
Searching the scene for objects is relatively slow, and it's also prone to errors
maybe not in this case, because there's gonna just be one player
but if you ever go from "one of X" to "many of X", that sort of code can cause undesirable results
ok got it will try, thank you !!
yea its working as intended thank you !!
now I can just drag the prefab enemy and it works
so now I can start the spawns.. 😄
Sorry guys i know a lot of questions haha - managed to spawn it after 5 sec but it spawns non stop instead of doing it once and waiting 5sec.. what could be wrong here?
Update runs every frame so you're starting a new coroutine every frame
I would do something like this
IEnumerator SpawnRoutine(float interval) {
while (true) {
yield return new WaitForSeconds(interval);
// spawn logic
}
}
Guys, I am using [SerializeField] and a variable below.. in player and enemy script works and I can see in inspector.. but created another script called bullet and it doesnt work there cant see in the inspector any idea?
Will
Vector3 positionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Just make a variable that stores the coordinates of the mouse?
Do you have any compile errors right now?
Oh yes I had but it was related to another thing that is not even connects, but removed the error and its working now.. got it.. thank you !! hahaha
your changes will not show up in the editor until the code is compiled
your code can't compile if there's even a single error
I don't know what that means.
Question. I have a method in my script Bullet, and inside the player but not managing to access this method from the bullet inside the player. any ideas?
look at your types.
private GameObject _bullet
_bullet is a variable of type GameObject
so it can hold a reference to any game object
yes
GameObject does not have a method called Move.
It doesn't matter that the object you are referencing happens to have a component that has a method called Move
but the gameobject BUllet has it and its here
the _bullet variable is referencing a GameObject.
Try dragging other stuff into the field.
Any object will work.
So there's no way you can call Move on _bullet.
I need you to understand that before I show you how to fix it
it's pretty important
ok wait I am trying to understand it, give me some seconds
but if I am dragging the object Bullet that contains the script Bullet and inside that script I have the method
why cant I access it?
let's clear up some terms here
you have a game object named "Bullet"
the game object has a component called "Bullet" attached to it
these are two completely unrelated things
the game object could be named anything
the "Bullet" component has a method called Move on it
If you have a variable of type Bullet, then you can call Move on it.
But you don't have a variable of type Bullet.
You have a variable of type GameObject.
The C# code has no way of knowing this object has a Bullet component on it, and that you meant to talk to that component
It just sees you trying to call Move on a GameObject and gives you an error.
like bullet = getcomponent<Bullet>(); and with that I can access?
You need to change the type of the variable.
Right now, you can put literally any game object in there
But that's wrong. You should only be able to put bullets in there.
So, change the variable's type to Bullet.
ok
Now the variable will reference a Bullet.
now worked, using the Bullet _bullet and now I understand
because using type GameObject can be anything and i was not saying WHICH one
If you drag a game object with a Bullet on it into the field, Unity will grab the Bullet component off of it and store it in the field.
i wanted even putting the prefab there on the inspector
And if you Instantiate that variable, it'll clone the entire game object
yeah ok, understood, that was an amazing explanation, thank you for that and your time explaning it 😄
public Bullet _bullet;
void Update() {
Bullet instance = Instantiate(_bullet);
instance.Move(...);
}
I almost never use GameObject variables
I always want something more specific than any GameObject
you're welcome (:
If I have a prefab for a UI element with an image and a text field, I will make a new component that references them
public ListEntry : MonoBehaviour {
public Image image;
public TMP_Text text;
}
and then I'll reference a ListEntry instead of a GameObject
foreach (var item in inventory) {
ListEntry entry = Instantiate(entryPrefab);
entry.image.sprite = item.icon;
entry.text.text = item.label;
}
much nicer than
foreach (var item in inventory) {
GameObject entry = Instantiate(entryPrefab);
entry.GetComponentInChildren<Image>().sprite = item.icon;
entry.GetComponentInChildren<TMP_Text>().text = item.label;
}
and if I add more stuff to the prefab later, my code doesn't break
this gets even worse if you start getting children by index or by name
a little tweak to the prefab can make everything stop working
Pretty much every prefab I make has a component that ties it together
Hi everyone, i have a problem on detecting the animation length by code... This code is supposted to do that... But it shows me 1 on the log, but the anim is quite shorter than that. This is the code and the animation length: ```cs
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
public class LoadingScreen : MonoBehaviour
{
private float loadingCanvasTime = 2.4f;
[Header("Drag")]
[SerializeField] private GameObject loadingCanvas;
[SerializeField] private Animator loadingCanvasAnimator;
[SerializeField] private Animator loadingTextAnimator;
void Start()
{
loadingCanvas.SetActive(true);
StartCoroutine(CanvasTextFade());
}
private float time;
private IEnumerator CanvasTextFade()
{
loadingTextAnimator.SetTrigger("ActiveLoadingFadeText");
yield return new WaitForSeconds(loadingCanvasTime);
loadingCanvasAnimator.SetTrigger("ActiveLoadingCanvasFade");
time = loadingCanvasAnimator.GetCurrentAnimatorStateInfo(0).length;
Debug.Log(time);
yield return new WaitForSeconds(0.3f);
loadingCanvas.SetActive(false);
}
}```
I have to say that all anims are on the deffault layer, i have not touched that. On the next image you can see the log and the anim duration
Why do you want to get the animation length? You should just use an animation event
hmmmm ok. so now changing the variable name I am able to access the method. But on this script here from the bullet I am doing the same but when I click the mouse button it gives an Object reference not set to an instance of an object. I need to also here put like _enemy = getcomponent<Enemey>(); to work?
getting an XY problem vibe here
By changing the type of the variable -- the name of the variable doesn't matter
You may need to drag the prefab in again
not variable name sorry variabgle type
If you changed the type, the inspector could show a reference, but actually be invalid.
I did it but its funny
it has the script simble there
and not the prefab even doing it again
cause i want to do something depending on the anim length... It could sound a bit weird... But it makes sense for me
Why don't you just explain what you're trying to do?
you don't need to rename anything here...
I've already said that... I want to check by code the length of an animation... But i like to say more details
The script icon is expected if you're referencing another component in the same prefab.
You get the prefab icon if you're referencing another prefab
!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
actually, you might still just get the script icon when referencing another prefab. i am unsure
I click there on the right and it says its the prefab but its not
Why is Bullet referencing the Enemy prefab?
Watch the Profiler for big spikes. You might have code that misbehaves when the time per frame is varying.
because i have a method in bullet that says go towards the enemy. and for the bullet to know where is the enemy
I imagine going frame-by-frame winds up getting rid of some of the randomness from editor code
Your bullet will need to reference a specific enemy in the scene
Referencing the prefab isn't helpful. It's the same problem you had earlier.
actually I am dumb I want to shoot in the direction of where the mouse is poiting.. jesus .. sorry for that confusion i will delete this
I am for 6h ctrying here just to move the enemy towards the player and do those things that my mnd isnt work.. i might need to eat something hahaha
It's more productive to take breaks
I came up with a big improvement for my settings system while making coffee this morning
what does this error mean
I have an inherited variable I want to downcast once instead of every time i need it. I could make a new one but i want to reuse code. what should i do?
sounds like a design problem
you could add a property that performs the cast
protected Parent foo;
Child myFoo => (Child) foo;
do you have a script named InputManager?
Can i instantiate like that if I am inside the gameobject script? Instantiate(this.gameObject, new Vector3(_player.transform.position.x, _player.transform.position.y, 0 ), Quaternion.identity);
This would make a copy of the object the component is attached to
i am trying to make when I click i shoot the bullet toward the player but I am getting a object reference not set to an instance of an object. always that error I might not fully understand yet this references .. always had problems that in the past in other stuff hahaha
yes
here it is
okay, nothing there looks alarming to me
so . . . I do not have an error?
Something is wrong, but it doesn't look like the code you shared should be causing any issues.
When do you get this error?
this will duplicate the bullet when Move is called
i tried to remove this part from the bullet script and put in player script where I call it, but it spawns but doesnt move..
you are trying to move the prefab again
Instantiate returns the new instance
ahh
The "game" runs without issue, so it just seems like a unity bug
I'm asking when the error appears
on recompile? when you start playing the game?
on recompile yes
get_main sounds like you're trying to access Camera.main
obviously that's not the case in the code you shared
The bullet isbeing spawned now but it doesnt move.. could be what u said or just my move logic
Move moves the bullet exactly once
I think you should compute the direction the bullet should go in
and tell the bullet about that direction
then the bullet can move itself in its Update method
this code is also not correct. the bullet's world-space position will change based on where your mouse is
But the mouse's position is measured in pixels from the bottom left corner
That has nothing to do with the bullet's world-space position
You need to use Camera.main.ScreenToWorldPoint to get the point in the world your mouse is hovering over
I would suggest doing it like so:
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = transform.position.z; // so the bullet doesn't fly out of the screen!
Vector3 dir = mousePos - transform.position;
bullet.direction = dir;
dir is a vector pointing from the player's position to the mouse's position
The bullet can then use direction to move itself every frame
from what I can gather it seems like you are trying to do something like this:
public class MyClass {
// init fileds
vector3 someVar = SomeUnityObject.Main; // <- auto init the variable with a unity variable
}
this is not allowed and you need to do it an awake, start, etc
public class MyClass {
// init fileds
vector3 someVar;
public void Awake() {
someVar = SomeUnityObject.Main; // <- init here
}
}
you would want to normalize the vector
Yeah, that's what the error implies
will try Thank you
But I ain't seeing it in that code
If you can't get it working, there ought to be lots of tutorials on making 2D shooting mechanics
Oh now the error is gone
ok thank you
I wonder if you previously had code that was causing the issue, and you just happened to notice the error after removing it
I have classes Weapon : Item, WeaponController : ItemController. ItemControllers have static methods that instantiate and return a controller. This method is called from virtual Item class method. so Weapon does this for WeaponController. but i cant reuse code in controllers because of different types. the static init method cannot be overriden at all. I need inheritance to keep the ItemController reference. How should i approach this?
Given an alpha map image texture, how to I apply it to a material?
(3d URP)
So one option would be to make ItemController generic. That would let each implementation of it return a specific type.
But then you couldn't just store an ItemController
you'd have to specify the generic type. no dice.
hm, how have I handled this in my own game..?
I mostly just work with specific kinds of items.
So I have types for weapons and consumables, notably
The top level item type doesn't have a method to create an instance of the item
The derived types do.
e.g. in my InventoryMeleeWeapon class:
public Weapon Create()
{
Weapon weapon = GameObject.Instantiate(spec.prefab);
weapon.spec = spec;
weapon.Setup();
return weapon;
}
I don't have a Create on InventoryItem.
You can't do covariance, unfortunately
public class Foo { }
public class Bar : Foo { }
public abstract class Parent
{
public abstract Foo Gimme();
}
public class Child : Parent
{
public override Bar Gimme()
{
return new Bar();
}
}
This is a compile error.
This would be convenient because calling Gimme on a variable of type Child would return a Bar, not a Foo
maybe i could make the static init method generic and only in the top class, other things i need to process
this is good advice, to add to it, you could also consider casting, depending on the use case. eg.
public void SomeMethod {
if(ItemController.GetStaticInstance is WeaponCotroller weaponcontroller) {
weaponcontroller.instanceVariable;
}
}
Yeah, that's basically what I've wound up doing
I did infact have some code like that that I deleted because it was the wrong code
public T ItemAt<T>(int index) where T : InventoryItem
{
if (typeof(T) == typeof(InventoryMeleeWeapon))
return meleeWeapons[index] as T;
if (typeof(T) == typeof(InventoryRangedWeapon))
return rangedWeapons[index] as T;
if (typeof(T) == typeof(InventoryBodyWeapon))
return bodyWeapons[index] as T;
if (typeof(T) == typeof(InventoryConsumable))
return consumables[index] as T;
throw new Exception("bad item type");
}
I don't like it...
its working now .. it goes where the mouse is, but it follows the mouse instead of just going straigh line to where the mouse was when I clicked. But I will eat something and try to figure it out this.. thank you a lot !!
also, again depending on use case, for inventories I've found that using an interface 'IInventoryItem' usually works in 90% of cases, since the inventory systems does not need to understand the concrete type
Right, the code to select a unit worked before, but now it does not- what mistake did I do?
I have many comments on this code. but what I would assume answers your question is that in InputManager
the line if(distance(unit.transfrom.position, positionInWolrd) > 1)
you might not want 'unit.transfrom.position' but rather 'unit.positionInWorld'
thanks
We don't fix AI generated code here. An effort has to be made. Thanks.
Yes it is Ai generated, I am trying to get a basic idea of how code works, but thanks for notifying me
I would suggest writing your own code.
If you want to try to get the basics of how code works there are tutorials pinned to this channel.
Thats what I will do when I want to make something that actually works
and thank you, I will check them out
Is there a way to do something like that, like that?
i mean i see its not possible like that so how would be the correct way ?
Why are you making the bullet instantiate itself?
That doesn't make any sense.
but for the cause of the error: Instantiate(this.gameObject) returns a GameObject, because you gave it a GameObject
Instantiate(this) would return a Bullet
trying to follow some stuff I see in the internet to fix my prob..
the guy in the video does like that and works for him
it seems i need to use rigid body to shoot stuff like i want
var automatically determines the type of the variable
He then gets a Rigidbody2D component from the instance
GameObject i tried but also doenst work
this code still makes no sense.
Oh it works fine
you need to stop and think about what the Bullet class is supposed to do
I don't think its job includes "make copies of itself when it moves"
But yeah why is it instantiating itself
well.. i am trying, if I knew how its done and where to put stuff I would surely have this done already 😛
Don't just look at these few lines of code. Look at where they are, and when they run
This is a script that shoots bullets.
It's not the bullet script itself. More like a gun script
Pay attention to the tutorial
Or whatever you're reading
you can write a perfectly valid line of code and still get bogus results
because the code is in the wrong place at the wrong time
got it.. now it works.. i can shoot it but the bullet get out sometimes faster or slower and also of course not in the mouse direction but that is next step now trying to use what you showed me before
now I am using it on the correct place that is why its working
you're setting the velocity based on the bullet's position
if the bullet is at [3,4], then its velocity will be [6,8]
damn, i wish I could see stuff like u that fast my mind is so slow yet to process info
hahaha
I am thinking about the meaning of each variable.
Position and velocity are different concepts
So it's suspicious to see them getting mixed together like that
You need to get the world position of the mouse, then subtract the player's position from that
This will give you a vector pointing from the player to the mouse
This is the direction the bullet should move.
but how do i set here a fixed velocity? if I put just a number it doesnt accept. bullet.GetComponent<Rigidbody2D>().velocity = transform.position * 2;
well, stop using transform.position first
once you have this vector, you just need to normalize it
still try like that
Vector3 dir = Vector3.right * 3;
Foo(dir.normalized);
worked 😄
In this script right here if i hold the Jump button will "hasJumpedThisFrame" stay true or will it turn false at the start and then true when it recognizes that im holding Jump?
It will be set to true every frame that you're holding the jump button
Because in the Console it says that it stays true
It will indeed be set to false at the start of Update
alright thank you
But then it'll immediately get set to true.
Were you expecting it to show up as false in the console?
I was expecting it to cycle between true and false but now when i think about it that doesnt make sense
yeah, there's nothing that would make it fail that conditional every other frame
You'd only see "false" if you logged it somewhere in the middle.
yeah i was logging it at the end lol
(and then you would only see false)
I have a really basic question: When i should use the Update() method and when the FixedUpdate() method?
I know the difference but i have no clue when i should use the one or the other..
https://docs.unity3d.com/Manual/ExecutionOrder.html shows the order of all the big messages
FixedUpdate is run once per physics update. Update is run once per frame.
FixedUpdate should be used for things that affect physics. This keeps physics consistent even as your frame rate changes.
Update should be the default.
This is a good video on it
https://youtu.be/MfIsp28TYAQ?si=aouK64dH1J6K0Ux_
Check out the Course: https://bit.ly/3i7lLtH
Learn how to move things properly with Update and FixedUpdate. We'll discuss the differences between them, why you should read input in Update and why you should move in FixedUpdate. We'll use a ball hitting dominos as an example of a character we can control and move around using wasd and...
Thank you guys!
So as soon as physics are involved FixedUpdate() is the way to go
More or less, yea. It's not 100% that, but I think that's a good general way of thinking overall.
Yeah.
Not sure if this is the correct place, but I've had a notion and was just wondering if it were possible. Is it possible to get the position/rotation/scale of a VFX Graph particle based on the position of the player and replace said particle with a prefab (and vice versa).
"based on the position of a player"?
Distance from player sorry.
I think the best place to ask would be #✨┃vfx-and-particles
currently working on the controller and physics for my "hover car f-zero type controller", my main problem is moving on things like this ramp, instead of smooth movement like moving on the normal floor it kinda goes up like on stairs. Anyone got an idea how i could fix that or maybe a better way of doing it than im doing it right now? thanks
btw im not using gravity on my rigidbody right now
well, you move the car up or down whenever the height difference exceeds a threshold
Are you trying to make it so that you smoothly rise up and fall down, instead of instantly snapping to the right height?
yep
In that case, instead of checking if the difference is too large and setting your position, you should just move a little towards the correct height every update
I would move towards the right height with at least a base constant speed
and then also increase the speed if the difference is large
I see that you have this restoreHeightSpeed variable
so maybe you're already trying to do it?
i got a variable "restoreHeightSpeed" which is supposed to to that
yea
but it works kinda goofy
what if you just get rid of the conditional?
guys could u give me a hand rll quick
basically what Im trynna do is this:
and it works sometimes
problem being
Im using raycasts
and what I do is after my raycast hit the wall
it will calculate a vector
and change diretion
please finish your thought before pressing enter
making so that it creats a new line renderer to show the deflected, the problem I have is that the raycast sometimes gets the origin point from the wall and collides with the same wall making it stop there and spawn all the next bounces in that same place
like this
any idea on how I could fix it?
you still haven't shown your code so how could we guess what you need to do to fix it?
📃 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.
this is the part of the code that is doing all that, I will try and divide it into smaller functions but for now Im trying to make it work as it is
hit.point-wallPos why this and not just the direction of the raycast?
I had the direction of the raycast but I was just trying random stuff to make it work
I'll change it
You can try adding a small offset to the raycast origin so that it doesn't hit the same point that it originates from
For example, hit.point + rayDirection.normalized * 0.001f
I did try that but it didnt quite work, maybe I didnt do it properly
+?
wouldnt I want to make it slightly before?
rayDirection is the direction of the next ray here
You get the point tho
Offset it outwards a bit
You can either use the ray's direction or the last hit's normal as the offset
how exactly should i do that? Should i constantly move the rigidbody to the wanted hoverHeight instead of checking if the difference is to large?
Red is the first ray, yellow is the offset, blue is the second ray, does it make sense? @uncut dune
oh yah I get what you are trying to say
I thought u were saying to using the offset in the last raycast
making the hitpoint a little behind
OK THAT SEEMS TO HAVE WORKED
THANK YOU SO MUCH
Noyce
Right.
Hi All - quick general question. Are hashtables a good method for enemies in games? I.e. to keep a certain number on screen and destroy the gameobjects at certain times. Or is this just unnecessary complication?
I think this might be a bit too general to get a good answer 😄
is there any way in unity to detect current time on your android device? or i have to use an API?
haha! I'm part way through a game with my brother. I'm quite new to coding. We've ended up using hashtables in our code for gameobjects and I'm finding it a nightmare to work with. Wondering if there is really any benefit to them. I feel like I'll have a bit more freedom and make things simpler without them
DateTime.Now
Why are you using Hashtables? What functionality do you need from it?
Just realized I've never used Hashtable myself. Usually I use the generic versions
thankss
I think it came from some random procedural generation code. The game is random as it progresses. So say there's platform tiles. Only ever 6 at a time, anything the players already passed get's destroyed and a new tile put at the front... so it can go on infinitely.
That method has then passed across in gameObjects like enemies and moving scenery etc. It works well for the random generation of tiles but I'm just thinking is it really a good idea for enemies? When I could just destroy the enemies of screen once the player has passed them using x values
You are asking is it good idea to use X without providing a reason to use X in the first place
it's better to reuse the enemy objects rather than destroying and recreating them. however hashtables aren't really necessary for pooling objects like that.
ah... reusing sounds like a good approach
of course you haven't even shown any code or actually explained how you are using the hashtables or even whether it is the actual HashTable type or the generic version which would typically be better
yeah was trying to keep it generic
What is the correct way to use the AddTorque function?
I am currently using Time.deltaTime and someone wrote that's not the correct way to do it (but it work's) 🧐
frontTire.AddTorque(breakingForce * Time.deltaTime);
backTire.AddTorque(breakingForce * Time.deltaTime);
Regarding to the docs https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddTorque.html i am not rly sure if that's a problem as long as it works in my usecase. Any opinions?
yeah you need to provide actual concrete information if you want help. don't just provide vague explanations to keep your descriptions generic
haha true
using object pooling, hashing and other fancy techniques are a good idea in general. but if this is just simple game to get to grips with Unity / coding. then I think I simple data structure like List will serve you better this time around.
it will let least get you where you need for the moment
you don't multiply your forces by deltaTime. you should also be applying physics (like torque forces) in FixedUpdate rather than Update
Yeah don't use deltaTime with forces/torques
they're already used throughout the game. And they're working so it's prob not a good idea to change at this time
that someone was me!
So the "Impulse" example at docs is what i should do?
and yes, it'll function
but it'll be wrong
the amount of force applied will wind up depending on your framerate.
or, if you put it in FixedUpdate, the amount of force will just wind up getting divided by 50
If you are applying torque to make your car move, don't use the impulse mode.
Just apply torque. That's it.
currently having some trouble with slope sliding, i start the slide on the slope, it takes a sec and boosts me forward and not down+forward, i understand the issue just not sure how to fix it
https://pastebin.com/TxnNCKL1
lmk if u need the whole slide script
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.
AddTorque tells the rigidbody you're twisting it with a certain amount of torque
so say I've got 5 gameObjects in a hashtable. Their x values can move positively and negatively.... I want to find x values on each update which are behind the player so I can destroy the game object and free up space in the hashtable for new ones to be created via the code already there. Right now I've managed to get the x values of all the game objects currently in the hashtable on screen. I was goingt o then create an array of these x values, then find the one's less than or behind the player to then destroy them. Problem I have is I don't know how to translate from the x values in the array to the gameobjects in the hashtable so as to be able to destroy them
the hashtable is irrelevant here. also you're still not providing concrete details on how you are actually using the hashtable if that is your concern
If I'm pushing on a box with one newton of force and the timestep is 100, I'm not pushing on it with 0.01 newtons per frame or something
it's just...1 newton, constantly.
Okay, i think i understood.
So if i do something like:
backTire.AddTorque(10);```
Every FixedUpdate, yes.
I could post the code but it's a lot of code and a mess haha
hahahaha fair enough
One (last) question regarding to the AddTorque topic. What's the common way to limit the objects speed?
Like right now if you press a button the car is always getting 10 torque and is accelerating like a rocket.
In real life, friction and air resistance (especially air resistance!) both increase as you go faster.
Try adjusting the drag on your rigidbody
If that makes the car feel too stiff at low speed, you could increase the drag as the velocity goes up, or something similar
video games can cheat with physics
you can also clamp the angularVelocity if you just want a hard speed limit
think I just need to read up on hashtables to get better at understanding how to draw information form them
yeah
iterate over the objects in the data structure and test each one to see if it should be removed
so i guess that means you aren't going to provide code to even show how hashtables are even relevant to your concern
since you usually can't modify a data structure while iterating over it, you can make a separate list to put the objects in
that's pretty much it.
I will mess around with that. Thank you!
A hard speed limit is what i will need (in combination with the drag). Thank you for the hint!
Hashtable and other non-generic collections seem pretty useless to me anyway
perhaps they mean Dictionary, yes
"hash table" would be a more academic name for the concept
About ObjectPool: I want to implement an ObjectPool for instances of a GameObject B, which can be used by multiple instances of GameObject A, but i cant figure out where to implement it so all As can access the same pool
yeah that's part of why i kept asking them to show code because they haven't even confirmed whether they are using the HashTable data type or Dictionary
ObjectPool is a reference type so either pass the reference around to all objects of type A or make it a static variable on the A type (but make sure to only initialize the variable once)
indeed
If every A can use the same pool, then a static field is reasonable
But if you might need to have them use different pools, you'll need to hand a reference to each of them.
i remade my code so it moves the position of the hovercar constantly to the desiredposition, but im not sure if its the right way again since my car now jitters mid air:
if (Physics.Raycast(transform.position, Vector3.down, out checkCarHeight, desiredHoverHeight))
{
Vector3 currentHoverHeight = new Vector3 (0, checkCarHeight.distance);
Vector3 desiredHoverHeightV = new Vector3(0, desiredHoverHeight);
Vector3 adjustHeightDirection = desiredHoverHeightV - currentHoverHeight;
rb.MovePosition(rb.position + adjustHeightDirection);
Debug.DrawLine(transform.position, checkCarHeight.point, Color.red) ;
print(currentHoverHeight);
}
@slender nymph @swift crag Thanks guys, I think having a single pool is good, because As spawn Bs in "spikes" and their lifetime is short. I thought that implementing the pool static in B would be a good idea, rather than in A, but stumbled over not being able to drag Bs prefab in a static variable of B...
Static fields aren't serialized, so yeah
One very useful idea is to make a dictionary that maps unity objects to object pools
each key being a prefab
Your new Vector3s only get 2 parameters. Is that intended?
so you say "gimme an instance of this prefab!" and the (singleton) object pool manager sees if it has a pool for that object yet
if not, it creates one
then it just looks up the pool and asks it for an instance
i didnt see that actaully, but does that make any difference?
unity just treats z as 0
Hey hey, trying to delete the bullet after 5sec, I already have the collision and it destroy when kill enemy.. but if it doesnt hit the enemy i want it to destroy in 5sec.. tried to use IEnumerator or the way it is here in the SS but is not working. Any ideas?
That sounds good. That "gimme" method would be static i asume and then getting access to that just by "using PoolManager"?
If PoolManager is a static class (or 'gimme' method is static) then you would do PoolManager.Gimme() @quiet dune
can you explain what "is not working " means
the bullet is not being destroyed after 5 sec
What is the type of bullet?
right. and what is bullet type?
If it is a component, you are destroying the component, not the gameobject
@swift crag @verbal dome I'll try that approach. Thanks guys
changed so now you can see better, removed the var .. its type Bullet
Right. So you are destroying the Bullet component only, not its gameobject
You want Destroy(bullet.gameObject, 5.0f)
oohhhhh
true
amazing thank you !!
I used like that in other script
example
and didnt notice my own
mistake
thank you
It's a common mistake
(two separate suggestions, btw)
right so- I assume that
if I click on a game object with this script and there is a unit selected, it will deselect it, right"
This script doesn't make much sense. Each object with this script has its own "selected" variable
You would need some kind of centralized manager to track the currently selected object
this is that centralized manager-
OnMouseDown shouldn't be here
It should be on the individual selectable things
Well, the centralized manager is also the map
Seems a little bit of a separation of concerns violation but, sure, should work.
but it does not-
OnMouseDown requires a physics collider. If this is a UI element you shouldn't be using OnMouseDown
You should use IPointerDownHandler
ah, understood
thanks
Still doesn't work-
You'd have to show what you did
oh sorry
right- okay wait a moment
what approach would people use to randomly move objects around?
could you just lerp to random positions over random times
could you just lerp to random positions over random times?
depends on the job of the objects moving around
You could do that yes
if it's purely visual background stuff, i'd maybe tween, for example.
it is background stuff yeah
but also background stuff that interacts at certain points in the game so lerping to a position near the player character might help me I'm thinking
don't know what tween is! Pretty new to coding
I do not understand this part of the guide on interfaces, and how to do so for IPointerClickHandler
How do I declare the interface in this case?
And what are the PointerEventData/are they needed in this case?
Write the interace, just how you do a class. Then implement the interface within the class you want to use it in.
Hi everyone! I'm having a little issue with void Update not being called. Right now I have 1 script with a class as follows "public class Placeable : Monobehaviour" and another script with "public class Generator : Placeable". Inside of the Generator class I have a void Update method which is not being called. I've tested it with debug.log. Can anyone tell me why this is not being called and if so how to fix it. thanks
just this?
For inheritance on MonoBehaviour, you need to mark the base Update() as virtual, and override it in the derived class
This is valid for all Unity messages (Awake, Update, Start, FixedUpdate, etc.)
How do I write this in C#?
Sorry I don't have the IPointerClickHandler interface off top of my head. I was explaining more of how IDamageable would work in a general sense.
Like SPR told you
But yes, implement, and define.
public virtual void Update() { /* base implementation here */ }
public override void Update() { base.Update(); /* call base class update, then implement derived behaviors */ }
thanks
You probably need to pass the methods some data though.
Also you need to configure your code editor so it highlights errors for you, and gives suggestions as you type
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
I want to have a character preview in the inventory. Much like in wow / rust / zelda etc. Is there any better way to achieve this than: 1. create a copy of the character model, 2. attach afront facing camera to it, make it render to a render texture, add that render texture to a raw image?
perfect thank you
well, thanks, on one hand it now deselects a unit
on the other hand, now it doesnt want to select a unit
nevermind now it
can't deselect a unit
Ill work on it tomorow
That’s the way. Out of the box this works pretty well: https://openupm.com/packages/com.yasirkula.runtimepreviewgenerator/
https://hatebin.com/kscjubftpo - script that changes the counter text in the inventory
https://hatebin.com/tqstuzqbah - script that adds the item to the stack
for the first item put into the inventory it is given 2 automatically instead of just 1
i cant find out why
how are you calling AddItem?
How do I change whichSprite in
void spawnAsteroidPT2(int whichSprite)
but inside of a function?
just within a simple button
Use Debug.Log inside AddItem to make sure it's not being called unexpectedly
alright
I don't understand your question
whichSprite appears to be a parameter to the function
you can pass in whatever you want when you call it
how do I do code box?
!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.
void spawnAsteroidPT2(int whichSprite)
{
if (//Anything)
{
whichSprite = //Anything
{
}
this isnt working
oops
it is not, it only ever happens for the first item added into the first slot
doesnt happen if it goes to the 2nd slot which is weird
maybe there's already something in the slot
thats true but then unstackable items would move to the 2nd right away, which is not happening
You need the three ` symbols and cs, follow the example
but it could be stacking it anyway which shouldnt be possible
Do you expect whichSprite to be changed where this function was called from? Because that won't work, integers are passed as value so it's a copy
oh you right
solved
an empty item data was sitting in it lol (actually 2)
Im dumb so I dont understand much but I want to change the whichSprite in void //blaablaa( int whichSprite // this)
the question doens't make any sense, sorry
Well, you can change it with whichSprite = something just like in your code
you pass it in as a parameter
it would accomplish little to change it inside, though yes you can always assign things with =
I want to change whichSprite within a function but it isnt working for some reason.
Explain your problem further
you are giving very few details
we can't help this way
It says "Unnecesary assignment of a value to 'whichSprite'
yeahn because it's pointless to change it
as I was saying
You put a value in whichSprite, which is not used anywhere, the error says
void spawnAsteroidPT2(int whichSprite)
{
if (whichSprite >=1 && whichSprite <= 5)
{
GameObject asteroidPrefab = asteroidPrefabs[whichSprite];
if (whichSprite == 4)
{
if (canSpawn4)
{
GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
TheAsteroid = Asteroid;
AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
if (Af.collided == true)
{
GameObject.Destroy(TheAsteroid);
}
}
}else if (whichSprite == 5)
{
if (canSpawn5)
{
GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
TheAsteroid = Asteroid;
AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
if (Af.collided == true)
{
GameObject.Destroy(TheAsteroid);
}
}
} else
{
whichSprite = 1; // DOWN HERE
GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
TheAsteroid = Asteroid;
AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
if (Af.collided == true)
{
GameObject.Destroy(TheAsteroid);
}
}
}
}
so you have to explain better what you're tryingf to do
📃 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.
!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.
Double kill
idk how this works
Look up how to type a backquote with your keyboard
(referring to the code you just deleted)
// the ` is left of the 1 on your keyboard
Depends on your layout/keyboard language
'''//like this?'''
{
if (whichSprite >=1 && whichSprite <= 5)
{
GameObject asteroidPrefab = asteroidPrefabs[whichSprite];
if (whichSprite == 4)
{
if (canSpawn4)
{
GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
TheAsteroid = Asteroid;
AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
if (Af.collided == true)
{
GameObject.Destroy(TheAsteroid);
}
}
}else if (whichSprite == 5)
{
if (canSpawn5)
{
GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
TheAsteroid = Asteroid;
AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
if (Af.collided == true)
{
GameObject.Destroy(TheAsteroid);
}
}
} else
{
whichSprite = 1; //THIS
GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
TheAsteroid = Asteroid;
AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
if (Af.collided == true)
{
GameObject.Destroy(TheAsteroid);
}
}
}
}```
ahhh I got it
mb im dumb asf
there is no point in modifying whichSprite it's a local variable. That's why you're getting a warning
Yep, now add the cs so it highlights C#
you mean to say you want to modify the variable that you passed in as a parameter
yes
myVariable = myFunction();```
and make sure myFunction returns the new value
that's all
ohhh I think I get it now
for exmaple:
int Example(int y) {
if (y == 1) return 5;
else return 0;
}
void OtherCode() {
int x = 1;
x = Example(x); // now it will be 5
}```
ty, c# has many rules I need to get used to
Now what is the point of that function? I see a lot of duplicate code
indeed
I tried to lower the amount of code using the parameter but it ended up being alot of trouble
I still am trying to learn to use parameters tho
{
if (whichSprite >=1 && whichSprite <= 5)
{
GameObject asteroidPrefab = asteroidPrefabs[whichSprite];
if (whichSprite == 4)
{
if (canSpawn4)
{
spawnSpec();
}
}else if (whichSprite == 5)
{
if (canSpawn5)
{
spawnSpec();
}
} else
{
whichSprite = 1; //THIS
GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
TheAsteroid = Asteroid;
AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
if (Af.collided == true)
{
GameObject.Destroy(TheAsteroid);
}
}
}
void spawnSpec()
{
GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
TheAsteroid = Asteroid;
AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
if (Af.collided == true)
{
GameObject.Destroy(TheAsteroid);
}
}
}```cs
I believe this would help a bit?
again you can't do whichSprite = 1; //THIS that is pointless. You need your function to return the value
Close enough I guess. What is the actual issue?
ik but thats not responding to the original issue just the copy pasted code
Might be good to explain what youre actually doing. Are you trying to spawn asteroids with random sprites?
my answer is a response to the original question
What is spawnSpec? I dont know whats going on
yes
Special asteroids which canSpawn4 or 5 must be true
I think I got it solved mostly
i have methods with the same scripts that i want to combine into one but cant because of types. There are classes B : A and C : A. 1 method: return new B(); 2 method: return new A(). I want to make method 3 that will return new A() that stores B() or C() depending on method parameters. So i want something like a dictionary[key, type]. is it possible?
methods can't "store" anything
they run code
if B and C both derive from A you can pass them around as if they are of type A
If you are having specific trouble with that you'll need to post your actual code and any errors you're encountering
when i said store i meant i need it to return base class instance that stores an inherited one so i can downcast
the base class instance doesn't "store" an inherited object.
You can have a reference of type A that refers to an object of any of the types A, B, or C
So using references of type A should work fine
If you are having specific trouble with that you'll need to post your actual code and any errors you're encountering
i dont have any troubles i'm trying to make a structure. i think you're misunderstanding the question
I think I am too. I don't understand what you need a dictionary for
this is all very XY
Asking about your attempted solution rather than your actual problem
What are you actually trying to do? Start there
Well i'm not going to ask you how to do class architecture, instead i'm asking a specific question. I need a method that takes a parameter key, instantiates an object of type based on this key (this is why i made a dictionary analogy), then returns base class that this type derives from that references the object. sorry if i cant make it less complicated
The existing Instantiate function satisfies your needs, assuming you use the prefab reference itself as the key
I can’t follow what you’re trying to do
Explain your use case.
Although, if I’m reading this right, you do just want a dictionary that maps this parameter to an object
Dictionary<SomeEnumType, Foo> options;
public Foo GetThing(SomeEnumType key) {
return Instantiate(options[key]);
}
if this is not what you're trying to do, then you'll need to explain further
heey, in need help, but I have to say that is not an easy help one... In the next code, all's correctly working excepting that when there is not internet, it always shows me the log ACTUALMENTE ES DE NOCHE and i don't know why is that appenning cause i've created the JSON file GameData for that... I hope you can help me... I would be really thankfull with you...
Please us !code to share your code as not all of us are allowed to download files (e.g. on work laptops)
📃 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.
have you debugged your code to make sure it's actually loading the game data correctly
no, let me try
sure
if (currentTime >= gameData.SunsetTime || currentTime <= gameData.SunriseTime)```
Isn't this always going to be true no matter what?
Of course it's goiong to print that
Oh didn't see Sunrise vs Sunset
still just print all these values out
it should become pretty obvious
@wintry quarry what?
i did what u said
@wintry quarry like this?
1, 2, 3, and 4 did not work
you set data, then read from gameData