#๐ผ๏ธโ2d-tools
1 messages ยท Page 34 of 1
Just make sure you don't have duplicate scripts or anything
I didn't
but it still doesn't work!!
the box is created and I can see it but it doesn't stop me from seeing outside it
you need to figure out that warning
See this?
See where it says "Script"
and it's grayed out
yeah
above your Camera Bounds
delete that
that's a broken script reference
and if you keep getting that warning, you have more of those in your project
when the game is running?
You do have errors disabled, but it appears like there are none anyway
ok and - what isn't working?
hmm - and you only have one camer ain the scene right?
Can you sahre your CameraFollow script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamFollow : MonoBehaviour
{
public Transform followTransform;
[SerializeField] CameraBounds2D bounds;
Vector2 maxXPositions, maxYPositions;
void Start()
{
bounds.Initialize(GetComponent<Camera>());
maxXPositions = bounds.maxXlimit;
maxYPositions = bounds.maxYlimit;
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 currentPosition = transform.position;
Vector3 targetPosition = new Vector3(Mathf.Clamp(followTransform.position.x, maxXPositions.x, maxXPositions.y), Mathf.Clamp(followTransform.position.y, maxYPositions.x, maxYPositions.y), currentPosition.z);
this.transform.position = new Vector3(followTransform.position.x, followTransform.position.y, this.transform.position.z);
}
}
this.transform.position = new Vector3(followTransform.position.x, followTransform.position.y, this.transform.position.z);
this line doesn't look right
should be this.transform.position = targetPosition; or something
right now it's ignoring all the bounds calculations that you're doing to get targetPosition
Thank you!!!
or rather - this.transform.position = new Vector3(targetPosition.x, targetPosition.y, this.transform.position.z);
your a savior
finally!!
okay so i'm trying to get this to work with Cinemachine but it wants me to create an empty game object with a box collider and rigidbody2D
this causes my character to get pushed out of the area, is there a way to fix this?
is it possible to change a box collider in sync with an animation loop?
oop, nevermind, I found it
different question
how can I pause my animation at a particular point to edit the collider?
selecting different keyframes doesn't do anything while the animation is paused, and if I try to pause during the animation, then the object just reverts to its default sprite
You can just scrub through the animation clip manually
that's what I'm doing
I think the problem is that my sprites aren't split correctly
my object shows as having the entire sprite sheet as its sprite
rather than individual ones
no matter what frame of the animation its on
oh wait I'm dumb
nvm, fixed it
is there a way to shave off the last 'tick' of animation at the end of a loop? I'm setting my last key frame to the same thing as my first one so that the pose before it can hold as long as I need it to, but the last key frame adds a little bit more animation that makes the first pose last longer than I want
Yeah, usually you just shorten it by a single frame
No wait
Keep it, but move the end marker back by a frame if you can
That's what I do in blender for smooth looping animations
Hi i spoke to some one last night but i still cant get my ai to face the player on trigger. Can any one see somthing wrong with my script
this is what i tried with the LookAt Method
@limber lichen This amount of code should definitely be in some external code hosting site. <#๐ปโcode-beginner message>
How can i create a chunk system?
@remote moth What do you need it for?
@still tendon What problem do you currently have with that?
for my terrain generations
to make the world infinity long, need i chunks
Guessing you'd save those 'chunks' as prefabs, and instantiate them when needed.
then would I have to completely rewrite the terrain generator?
is there an alternative to chunks?
That'd depend how your terrain generator works, and what you mean by chunks exactly.
i mean chunks how in minecraft
For an infinite world, you need a generator that can generate chunks one bye one, instead of the whole world in one go. The problem is usually to keep the boundary between chunks consistent
Then you create new chunks of the world as needed
Don't cross post, please. :p
@tribal gyro Yea don't cross post.
collisions.above = directionY == 1;
can anyone tell me how does the relation and assignment work her
here
collisions.above (a bool) is set to the outcome of (directionY == 1), which returns a bool.
So collisions.above becomes true if directionY is 1.
got it
In other words...
= set to
== equals
can i use transform.translate with Vector2 with no issue for a 2D platformer game
anyone know the issue
Here's the documentation on the error. https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs1040
Basically you have a preprocessor directive (anything starting with #) on a non-white line. So if (true) { #if UNITYENGINE //blahblah would cause that, I guess.
can i use transform.translate with Vector2 with no issue for a 2D
your Vector2 will be automatically converted to a Vector3 with a zero z component. Should be fine
You have a preprocessor directive in your code with whitespace before it. E.g. #IF UNITY_EDITOR
you can't have a space before it
i just deleted the file and started again ๐ it was only a few lines so it was fine @snow willow
public class Enemy_Follow : MonoBehaviour
{
// Start is called before the first frame update
public float speed;
private Transform playerPos;
void Awake()
{
playerPos= GameObject.FindGameObjectWithTag("Player").transform; (TH)
}
// Update is called once per frame
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speed * Time.deltaTime); (TH)
}
}
``` what does this code do , ESPECIALLY CONFUSED WITH THE PART WITH (TH) , all i have understood is that players position is equal to the object with the player tag position and yeah thats pretty much it
in the first TH you find a gameobject with the tag named "Player" and assigned it's position to playerPos variable
to be specific the transform
in the 2nd TH you changed the position of the current object the script is attached to. To the position of the gameObject with Player tag
in the 1st Th to get the position you need to say
playerPos= GameObject.FindGameObjectWithTag("Player").transform.position;
Hello there. I am having a question regarding SpriteMask overlapping. On the image I have 3 objects:
- The tall grey rectangle, that has SpriteRenderer & SpriteMask with the same sprite.
- The 2 "crack" SpriteMasks.
- The wide black rectangle.
The gray sprite is set to "visible outside of the mask", so it is transparent at the cracks. The same object's mask (the orange outline) is set on a custom range so it doesn't affect the gray area.
My problem is that I don't know how to make the black rectangle to be shown only within the gray mask (which it current is, the hidden parts are outlined in blue), **and ** to be transparent on the cracks (which it currently isn't, the desired transparency is outline in red). In other words, I need the black area to be visible inside one mask (the gray), and outside of another one (the cracks).
thank you , very much appreciated ๐
Hi, Anyone know a good tutorial on how to create a fog effect for 2d top down please?
Hello, Im having a bit of trouble with making 2d platforms. Im using a prefab, but when it is created in game, im getting some sort of sliding motion
add a physics material to your players rigid body and set the friction to 0 @keen solar
Thanks
I'm creating a RawImage using a Material based off the Hidden/BlitCopy Shader and set its _MainTex to a RenderTexture. This RawImage is then displayed in a Canvas. This works fine, but when I try to replace the _MainTex with a new one after initially having set one my displayed rawimage just becomes black. The only workaround I found is creating a new Material. Am I missing something?
Found it, SetMaterialDirty is what I missed ๐
I have this problem where despite having setup OnEnterCollision2D events they never trigger for some reason, i've added box 2d colliders (for reference im checking for collisions on a bunch of prefab clones all in the same parent)
Are your box colliders triggers ?
no, though ive tried re-writing as triggers and no dice :(
i have not tried, though organisationally that will look horrible
i will now thanks
i have tried with and without rigidbodies and nothing
The 2D ones, right ?
yeah
Can you screenshot the inspector for your object ?
Did you try changing static to dynamic
No judgement, don't worry
we're all learning here ^^
Nice ^^
Do you happen to know how to make it so that my camera shows the same things when changing the size of the screen ?
I have this button on screen that isn't correctly shown when going full screen
It's ok if you don't know ^^
Canvas scaling should deal with that
Just need to make sure your anchors are set up correctly
Oh right, I'll check that. I'm not really used to canvas ^^
Thanks
Oh, I found my error, it was that I set the game aspect ratio to free aspect
@azure aurora That is not the error, it just allows you to see the issue
Undocking the game view in free aspect and resizing it is a good way to see how it will behave on various screens
Ah, I see
Well, it seems like a complex problem to handle. I'll deal with that later in developpement
i have already asked before but after trying for like 1 hour i still did not get out: how do i make my game work with other espect ratio's?
my friend see :
i see:
@wet glen If your camera is orthographic then you can use a script like this to (in the case of this particular script) force the camera to match a specific aspect ratio by adjusting its orthographicSize size property.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetupCamera : MonoBehaviour
{
[SerializeField] float _initialSize = 5.0f;
[SerializeField] float _targetAspect = 1.777778f;
void Update()
{
float newSize = _initialSize * (_targetAspect / Camera.main.aspect);
if (newSize != Camera.main.orthographicSize)
{
Camera.main.orthographicSize = newSize;
}
}
}
yes it is orthographic
what shood _targetAspect ? be shood that be 1920/1080?
o wait it already is
Yes, that was for a game designed for a 16:9 aspect ratio.
You don't get black bars though. That is, on a 4:3 display, you will see whatever is above and below what a person would see on a 16:9 screen. (Hope that makes sense.)
No, that script basically forces the camera to match the designed width of the game.
so what do i do now?
Well, if you want to play around with that script then save it as SetupCamera.cs, attach it to your camera and set the two properties. Initial Size needs to be set to the camera's designed Size property.
yeah i have done that.
but does this also force the height to work @tropic charm ?
You can make it force the width or the height. You can find similar scripts that will force the height.
but i cant do both?
No, however, if you are going to run as a native app on Windows, Linux, or MacOS then there are command-line options to do that. I'm sure there's a way to use this feature programmatically as well but I've never done it.
If your game will run on the web then I don't know what you would do.
i must be missing smt, i just want my content to be the same on each device?
but I cant do that ๐ฆ
Yes, if you want your game to always use 16:9 (or whatever) then look into the player's command-line options.
And see if you can do the same thing programmatically, so the user doesn't have to use command-line options.
Look for the Unity Standalone Player command line arguments section.
You can use the -screen-width and -screen-height options to specify a 16:9 resolution like 1920x1080.
They likely design their games to support a range of aspect ratios and then either match the height or width, depending on the game.
They may also do something similar to that script but then clip any content outside of the designed-for area.
Hey hey
For someone who has more experience:
Am I doing anything wrong here?
_cellpos = GetComponent<Tilemap>().WorldToCell(mouseWorldPos);```
_cellpos.x and _cellspos.y simply return the mouseposition rather than a cell
what am I missing?
mouseposition is screenposition i think, gotta use camera to turn that input to world position, then pass it to world to cell (if im right)
Yep
Correct.
I then spent 10 mins fumbling with screentoworldpoint
and then figured it out
Hi, Does someone here knows how to use unity's A* algorithm with an hexagonal tilemap?. I've found this video where a guy uses a square-shaped grid instead of an hexagonal one and I don't know how to change it to hexagons.
https://www.youtube.com/watch?v=HCt_CYOW9jg&ab_channel=CodingWithUnity
How to implement A* into Unity3D's Tilemap system.
Project includes graphics, and scripts
โDownload Project: https://bit.ly/2Nz1waU
โDownload Graphic Asset: https://bit.ly/2zpXyhf
โA more in-depth Astar explanation: https://bit.ly/2GLlu1A
โฅ Subscribe: https://bit.ly/2FRWgOi...
The only difference will be that you have 6 neighbours instead of 4 when exploring new tiles
@broken dirge
I don't understand the video though. It does everything *but ** implementing the A
thx i try do it
I needed a way to create screenshots of all my tilemaps regardless of camera position. May or may not be useful to you guys, but it works for me. YMMV.
https://gist.github.com/ryanbyyc/6c86414dbec607162c89fe315e75dc8f
I'm trying to use A* Algorithm with an hexagonal tilemap and Iยดm not sure about how to make the neighbours comparisons . Could anyone give me their opinion?
https://hatebin.com/kyztwdkufw
can someone help me with my spring-type code i keep getting this error
my code^
GameObject doesn't have a "rigidbody2d" property
Seems like where you might want to use bouncer.GetComponent<Rigidbody2D>()
srry for ping but I've been on this for a while
Show the code
Also for future reference send the code not screenshots
ok
That isn't valid since the GetComponent() method returns a value
But you're not storing that value in a variable
Also what property of that component are you trying to change
You need
var component = bouncer.GetComponent<RigidBody2D>();
im trying to make a spring type thing
Yeah I have no clue what you mean
like a spring when you jump on it your character goes high like a jump
Yeah I can't help you with the theory only the code errors
ok thanks tho
@snow comet do you know how to fix this?
same code, but i put in what you said
Press Ctrl + .
Nevermind, there's a spelling mistake
It's Rigidbody2D not RigidBody2D
I highly encourage you to read and understand instead of copying code
thanks, i will, i've just been stuck on this for a while and wanted to get it over
np
what would be the best approach in creating a moveable gameobject that can only be moved by a player?
give the player code that allows it to move the object
so i have this problem where i want to stop physics objects leaving the screen so i've put a edgcollier around it but sometimes objects still phase through, is there any way i can stop things popping through a rigidbody
just physics
the wall does stop it mostly
but sometimes there's a lot of force and it just pops through
physic stuff run in FixedUpdate, and you usually move it with something like AddForce
so the'res no clever way of doing it, just no force vectors offsceen?
okay so i could use good practicce
or i could get out of bounds objects to just teleport back in
tysm for help though
just get screen size and object position
I have a problem that my character cant move...can anybody help me?
That is not the callback for FixedUpdate...
you spelled it wrong
Well, capitalized it wrong
oh thank you so much
How would i go about destroying a gameobject that has left my screen (actually a little bit further than my screen, OnBecameInvisible() wouldn't work for me)?
You can destroy it anytime, or do you want to destroy it when its out of view? @pallid kayak
yes, when it is out of view
Then you have to have som ekind of renderer on it to make the onbecameinvisible work.
i have made a second camera attached to the first one, can i use onbecameinvisible now?
the second camera's ortographic size is larger
i believe this should work
Okay, 2 things to concider, if you test in playmode, your scene view acts as a camera too! So you have to hide it to actually only work with your camera. And if you have two cameras, be sure none of both sees your object.
my second (larger) camera is attached to the first one
how do i select which camera to use? my game view seems to prefer the camera i just added
change your camera depth
they write to the screen in order of depth
so higher numbers will be on top
got it, thanks
it does not
the asteroid does not disappear
made a capitalisation itsake
trying again
it works now
well, okay ๐
In unity 2d, how do I make a player's sorting position update based on their position? I have tried everything I could find (Which wasn't much) and I just cannot get it to work. The main problem is that all the solutions that i did find, are for people using sprites whereas i'm using tilemaps. I just want a simple system in which the player can walk up to a wall and be in front of it a bit, and the same thing behind the wall.. Anyone got any ideas?
(it's for a 2.5d topdown game, think pokemon or enter the gungeon)
See step #2 of this tutorial. In fact, if you are creating a top-down style game I highly recommend you read the entire tutorial.
Now that youโve created the base of a world for the character to move around, you can add some GameObjects to decorate. In this tutorial, you will: Decorate the world youโve created Customize the way that Unity renders your Sprites Reuse GameObjects using Prefabs Want to learn more about 2D Game Development with Unity? Connect with an expert Un...
It is a really good tutorial. Good luck with your game.
okay sadly the tutorial did not really show me anything. i had already tried all of these things.. @tropic charm
mostly as this is again about seperate sprites and not tilemaps
Like is my only option to just build the level with seperate sprites besides the floor for which I can use a tilemap
Ah gotcha! I misread your original post.
I've messed around with what you are trying to accomplish and, yes, it is tricky. I think most people split the tilemap into two layers. One that the player is always in front of and another that they are always behind. The designers don't let the player walk anywhere that would be problematic so far as the draw order goes.
hmnm
Use sprites if you want proper draw order, I suppose. Tilemaps for everything else. It might even be better to draw the map in something like photoshop to get better division between the layers.
You could split tiles between layers that way.
but alright i got it working like you said yea
just make the colliders a bit bigger to prevent the player from goin there
it works like this
thanks!
why do i cant see the apple?
Is it a sprite or a ui object?
Make sure the z axis is at 0 or above the background z axis. Also, check the 2d layer it's in. It needs to be above the background layer...
i dont know how to see it...
i got it to see, but the background is now black
i think its sprite
How can i spawn platforms infinetly around the player in both axis?
but i dont want them to collide or be too close
any resources for creating skeletal animations or sprite sheets using vector art?
plenty of resources for doing either technique with pngs, and importing vector art via SVG Importer seems simple enough
Change your Order in Layer in your spriterenderer
you mean the grey background around the apple? does the apple image have a transparent background or is it black?
Hi guys. I have another issue.
i have created a empty object
i have a button
i have the code/script written correctly to get the game to (Application.Quit();)
its connected, and the function is selected in the dropdown menu
however, nothing happens when the game runs.
the debug.log dosent show either. any help would be greatly appreciated
show screenshots of your setup
Yeah that's teh part that's confusing me
that part should work
but Application.Quit() doesn't work in the editor
here's my quit game code for reference of what you need to do:
public void QuitToDesktop() {
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}```
ok...
But yeah the debug.Log should still be running I think
but aside the fluf. i just want a hard quit/exit
even if the Application.Quit doesn't work
nothing pops up
No I get that - Application.Quit(); doesn't do anything in the Editor is what I'm saying
sorry.. little stressed with the simple codes not working
If you put the Debug.Log before the Application.Quit(), does it print then?
i can get the coins and pain images to spawn but this dosent work
Whats the error?
no
it dosent change, before or after
i do know that most things are to be put before the exiting code to make sure it hits it, but this case, it dosent respond one way or the other
and its crazy, i can get this image/scene to show for a game over, so its loading but not exiting
i have the same issue with the restart button
One thing that may be hurting
no error, just nothing,
I see you have some warnings about missing scripts etc..
that may be causing an issue
you should go clean that up
thats on player pain, im setting it up for lives
this is like, legit my first game.
Okso if nothing is working at all there may be an issue with the raycast hitting your button
? i reset everything to 0..
If you look in scene view, are there any other UI elements that may be overlapping with that button?
Another way to debug. Find your EventSystem object in the hierarchy
and click on it
so that you see its inspector on the right side of your screen
then at the bottom, you should see a window like this:
Then while you are playing your game, your EventSystem will update that window with various information about what UI object you are hovering over and clicking on
when you try to click on your button, see what object shows up there
If it's something other than your button, then something is blocking the button
ok
should i outright add it , i dont see it added to any of the objects
(btw do you get the various animations for your button as you mouseover and click on it)
If you don't have an event system at all
that's your problem anyway ๐
You should also double check your canvas object
and make sure it has a graphic raycaster
ok
2D/3D doesn't matter
I got an issue. I have a damaged animation and I am trying to get it to play for one second in my code before it turns off the trigger. What is a good way to set a one second countdown for a trigger in c#
So double check that you have this:
- An EventSystem anywhere in the scene
- An InputModule on the EventSystem object
- A GraphicRaycaster on your Canvas object
Your C# shouldn't handle that at all. That should be part of your animation clip/animation state machine
The C# code should just set the trigger
and the animator will handle the rest
assuming you set up your state machine properly
thank you, will check
so far, none of the images/btns have any event handler face palm
I need to have it turn off the trigger after use and the animation play. Should there be a way to do that in the transitions?
If you have a transition based on a trigger, the trigger will be "consumed" as soon as the transition happens.
i.e. when the transition reads the trigger, the trigger will be unset automatically
that's the difference between a trigger and a bool
i have this error, the code here is the code anchored to the enemy ships that instantiate every 5 seconds, the code is suposed to rotate the ship to the position of the player, but aparently they just aim the player in first frame and no more
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAiming : MonoBehaviour
{
public Rigidbody2D rb;
private GameObject player;
private Transform playerT;
private Vector2 target;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
playerT = player.GetComponent<Transform>();
target = playerT.position;
}
void FixedUpdate()
{
Vector2 lookDir = target - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg -90;
rb.rotation = angle;
}
}```
You're only raeding the player's position once in Start(). It never gets updated after that
You're just saving it in that Vector2 variable target
i understand, what should i do to fix it?
You would have to change the code in the FixedUpdate to this:
Vector2 lookDir = playerT.position - rb.position;```
get rid of the target variable entirely
๐
have a good day
or night
or whatever
oh
i almost forget
i have another problem
this is with the enemy spawning
i have this error, im making a clock that registers the time (left down corner) and i want it that each 60 seconds the time between each instantiated enemy is reduced by one second, but idk why does not work ยฏ_(ใ)_/ยฏ
When you want to compare for equality you have to use ==
= is the assignment operator
it sets the thing on the left to the thing on the right
that's why the error is sayting "the left hand side of an assignment must be something..."
it things you're trying to do an assignment
regardless - instead of writing wave1 == true
you should just write wave1
wave1 is already a bool
so by writing wave1 == true it's like writing true == true or false == true
you don't need the second == true part at all
lmao ok
e.g. if (Wave >= 60 && wave1) is perfectly valid
it may be fine as a beginner to leave the == true if it helps you though
ok, error fixed, man, you are so good, you are even explaining me how the code i used works ๐
I switched from bool to trigger. How do I get the animation to play for one second when it triggers? I am in the animator.
That is now controlled by the animation clip
and the speed you have for the animator state
So do I make it so itโs not interrupted and then make the clip one second worth of sprites?
so in your animation clip
Long story short trying to trigger a damage animation to play for one second to let the player know they were hurt. I want to pair it with a minor knock back to move them away from the enemy.
you should have it run from 0:00 to 1:00
let's start with the clip. Is the clip 1 second long?
I will play with that now. Thanks! I am am new and done pretty well so far. Thank you!
once you have the animation clip as 1 second long, we will move to the next part
you should be able to preview it in the Animation window and it should play for 1 second.
Thanks. I think I have a knock back from beachys I will watch. Try to do it on my own first.
sure
Been using him, unity learn, and GitHub
@snow willow i wound up deleting the entire scene, but i have a new question
i was following a youtube link, i wanted to know if it was still valid
is it ok if i post it here?
np
๐ Support me and DOWNLOAD Unity project: https://www.patreon.com/posts/46483799?s=yt
This tutorial/guide will show you how to create a simple game over screen for you game that will allow players to restart the level or even go back to the main menu
๐ Join our Discord: https://discord.gg/hNnZRnqf4s
๐ต Follow me on Twitter: https://twitter.com/b...
I never said it was a good tutorial
Unity should be creating an EventSystem automatically (you're talking about EventSystem, right) for you when you create any UI object
yes
If you look at that video at 1:10, you can clearly see there is an EventSystem in his hierarchy
I think Unity probably created it for him automatically
it usually gets created when you create any UI object from the menus
so
when creating this scene
he creates it within the main scene of the game
when i did that, the game over screen overtook/covered up the game screen
dose it matter if you create a seprate scene or a subscene?
Sorry for being too technical
Hi everyone! I am creating a project that is a 2D dodging game. I am having some trouble with the pause button and the pause button code. if anyone could help, it would be greatly appreciated!
I tried a couple of things with my code
Sorry about the messiness
Try this script...
// PauseGame.cs
using UnityEngine;
public class PauseGame : MonoBehaviour
{
private bool _isPaused = false;
public void TogglePauseGame()
{
if (_isPaused)
{ // Currently paused. Resume game...
Debug.Log("Resuming game...");
Time.timeScale = 1;
}
else
{ // Currently running. Pause game...
Debug.Log("Pausing game...");
Time.timeScale = 0;
}
_isPaused = !_isPaused;
}
}
Attach that to your button and setup the onClick similar to this...
If you don't see those debug messages then you've done something wrong.
transparent
HI! I currently working on a combat system for a 2D top-down game. For Hit detection I wanted to use colliders as hitboxes, but the game would allow for different types of weapons, each type with a different hitbox. The most simple approach would be to just create gameObjects with the various hitboxes but I was wondering if anyone could give me some pointers for a more flexible system that allows me to adjust the hitbox pretty much however I choose.
Hm, not sure if its worth it but you can use the meshrenderer bounds to get max and min values of your mesh and therefore swap out the collider size @frank vector
That would however only allow changing the collider size. Still would have to create collider shapes for each type (line, arc, circle etc.). I was thinking about maybe creating polygon colliders at runtime (basically onbutton"attack" -> check weapon -> create collider), but I'm worried that may impact performance.
Do you need pixel perfect hit detection? if not, you could just create an approximate collider box in the general attack direction
No don't necessarily need pixel perfect hit detection. I think I will play around with the collider creating idea and see how much it impacts performance based on number of enemies. Thanks!
You also have things like Physics.OverlapBox(...) (see https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html) at your disposal; you probably don't even need colliders, just a logic that gets handled OnAttack
Oh I actually did not know about OverlapBox. I think that may be very useful! Awesome, thank you!
What sort of hitboxes are you trying to create? Often several physics queries are made from previous weapon position to current weapon position to model the attack as it happens
When trying to model reasonably very accurate hit collision
Of the top of may head: A straight line hitbox (spear), an 45ยฐ arc hitbox (swinging axe), a circle (hammer) and maybe a rotating arc collider (spinning attack).
The queries would look something like this:
PhilSA talks about the method on the forum: https://forum.unity.com/threads/thoughts-on-implementing-precise-framerate-safe-melee-weapon-collisions.462087/
Thank you, I will take a look at it
the life text is in the game scene in the right corner, but when i build the game the text is not in the right corner...?
Gotta set up your anchors properly. Anchor it to the top right
what are your recttransform inspector settings ?
the cam settings? or what
Cam??? No the anchors on the rect transform
I guess your resolution on the game view is not the same as your build running device, so your UI is not scaling properly, maybe because of what @snow willow said about anchors or your whole Canvas is set to a specific Resolution or not scaling.
sorry my main language is not english lol
This is setting your object to a specific offset from the center, so if your resolution gets higher, the offset will not be on top right.
okay... so what i need to enter in there?
I recommend watching a little tutorial on youtube about rect transform and anchors, so you undersatnd, what its doing ๐
i dont want create a big game its just for a school project
You want your anchors to be all 1 and your posx and y be 0 or whatever fits your visuals
Coding question. I need to check if "amount" is negative and "IsInvincible" is false before setting a trigger. I can't seem to get the if statement right. What should the if statement be?
Right now the issue is the damage animation plays when I gain health
It just asks for the amount to check for invincible, after that it will always play the IsHurt triggered animation
Well the issue is it's playing when I get a health pickup
I wanted to add a nested if statement of "If Invincible or amount is above 1"
Yeah, you are never asking before setting the trigger it the amount is below 0
you are getting into the if statement, ask < 0, then exit it and just play the trigger
You should put that trigger into your if statement at the end of it
I was thinking
If (isinvincible && amount >0)
{
Play animation
}
but not sure the exact code I can't seem to get it right
if your amount is < 0 && !isInvincible, than play hurt animation, else if amount > 0 play health animation
Invalid Expression <
this was just written out, no code... remove the "is"...
I did, still having a slight issue. I think I get the basic I will play with it. Thank you
Yw
Got it working thanks!
Now I just need to figure out my animation tree it's having issues switching to damage while falling
Cool its working
Is there a way to prevent clipping into the ground like this?
So i have a map generator that creates a map. Now I want to put tiles on the map, hopefully using rule tiles or something similar. I got it working (see screenshot), but in order for that to work I had to manually create 64 different rules (16 for floors, 48 for walls due to corners) with 64 different tile variations. Also, i now have basically upscaled the resolution of the map because each 1 unit for the map is 32 px, while the actual tileset and character resolution should be 16 px - i can scale the characters up as well, but that probably will look shady. Is there a better way to actually accomplish this while keeping the overall resolution intact?
hey guys dose any one have an idea about how to manage to move the scroll rect that contain the inventorys items on it up and down when u select an item in the inventory??
without moving it with the mouse
thank you ! โค๏ธ
If you can figure out the correct value then you can use the verticalNormalizedPosition property.
@peak stirrup do you have a tilemap collider on your tilemap and some collider on your player?
@uneven shuttle are u asking two questions in ur message
for the scale, you can scale your entire tilemap just using its transform, but there are also scale options in the tilemap component
(or the grid component, dont remember)
@split lava yes, I have a tilemap colider on my Tilemap and a box colider 2D and a circle colider 2D on my player
can you explain what happens when the player clips into the wall more in detail
If I land on the floor from high up or hit a wall or ramp moving fast it goes inside
oh thats a pretty simple fix
just go to your player's rigidbody and change collision detection mode from discrete to continuous
lol no problem
can anyone help me with a sprite problem ?
i have a list of total sprites in the game.
then i randomly pick a few of them , putting them into a fixed array.
i'm trying to grab each one of these sprites and put them into a spriteRenderer to display all of them at the same time, but all i'm getting is the final sprite that is in the array. and also it's accessing the spriteRenderer of the GameControl in the hierarchy not the ones from the sprites that are in the array
code for clarity, with a lot of log
okay this is my code, works fine but it dashes on arrow keys, how to i change that to for example
so z + w forward dash instand of arrow key etc. https://hatebin.com/klqcjgwhnn
Trying to get my char to stick to the platform. It moves without them and I have not been able to get them to stick. I am using some code I found on a site for suggesting platforms and tried to alter it a little.
Using this great code and not sure how to make it take my platformer char with me
I added RigidBody2D to the platform and changed it to update contentious but reading how to I can't figure out how to set the char to add the platform's velocity.
Woot! Got it working! Found it on Unity Forms
So i've got a field of view working, essentially just by shading the tiles with a different color. Just wondering, would there be a way to smooth the edges to not make it look as tile-y?
thank you i just managed to get it right still nooot perfect but i used scroll.value += value and scroll.value -= value for up and down control still its not sync with the items in my inventory :p
I'm trying to make a sprite jump, but whenever I add ForceMode2D.Impulse it doesn't move whenever I call the function compared to if I just leave it out
I've looked online to see what the issues are but changing the rb to dynamic doesn't fix it
Does anyone know where I'm going wrong with this?
IIRC it's the height of the top of the visible area of the scrolling pane.
So they normalised distance from the top of the plane and the top of the visible area
If that helps
Just realised I posted in the wrong area again blegh xD
question:
how would i make "wires"
you can drag the ends to manipulate the shape
my current guess is to have two gameobjects, then a line renderer that draws between them...?
You could technically do
if (collider is BoxCollider2D boxCollider)
{
}
but I think most properties in the Collider class are just overriden in derived Collider classes, so you might not need to even cast it like this
properties like bounds are in the base collider class, and would be accurate without casting to the derived version
I tried seeing if I could get some properties but it didnt work
Specifically I need the center
isn't there bounds.center?
Ooh I think ur right loll
Doesn't that mean it's flipped, so facing away from the camera?
The height/width is probably a negative value
@tropic stream
im looking
weird it was flipped..
@fallow tendon Do you know why my text isn't where it should be, when i build the game?
@tropic stream when you do UI it's better do use game view instead of scene view
then you can know if it's actually fliped because game view UI doesnt move
and in scene view you can by accident go 'behind' your UI
try game view and tell me if it's flipped there too ?
big guess from me but maybe the screen size/resolution on build is different from testing and it's getting pushed around based on that
i made now a new resolution (1920x1080)
hey! thank you for your reply to be honest i dont know mush about IIRC but i found a thread in that talk about this issue i try there solution and it works! here is the function if anyone have the same issue
and here is the result !
im sort of confused with this code could someone help
private Transform playerPos;
void Awake()
{
playerPos = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3(playerPos.position.x, playerPos.position.y, transform.position.z);
transform.position = new Vector3(Mathf.Clamp(transform.position.x, -3.4f, 3.4f), Mathf.Clamp(transform.position.y, -2.86f, 2.86f), transform.position.z);
i want a code for 2D for movement (jumping , moving) . I m not a very good coder and i want a code to put in my game .
@gaunt tulip Help with what?
So i am trying to make a answer box, and when the answer is correct i want something to flash green, and when its wrong i want something to flash red.
I have the code working on an if else, and it works right now with saying "correct", "incorrect"
I was thinking of using a coroutine that set a panel to active, wait, then set active to false, and use a float value to control how quickly this panel turns on and off, so it will look like it is flashing after the answer is correct
PROBLEM: When i open the menu before answering anything the panel turns on, waits, turns off then thats it, it does not happen every time the IF statement tells it to
Is there any thing in coroutines that i need to return to have it happen again? Or can you not put it in a If/else statement?
or is there anyway to get a WaitForSeconds, outside of a coroutine
Coroutines run to completion, and when they complete, they go away.
if you wwant something to repeat in a coroutine, you would use a loop
IEnumerator DoSomething(int numberOfTimes)
for (int i = 0; i < numberOfTimes; i++) {
// do something
yield return new WaitForSeconds(1);
}
}```
so it doesnt work in a if else then? meaning i can not execute it each time i need it to?
I'm not really sure what you mean by that
if/else statements work inside coroutines like anywhere else
Maybe share your code?
ok so...
on line 27 right now
you're just calling waiter()
which isn't how coroutines work - that won't actually make any code inside waiter() run
you need to use StartCoroutine(waiter());
i see, im sorry im good with unity, bad with hard coding, let me try calling it like that
@snow willow you are my hero, if there is anything i can help you with please let me know
"IIRC" means 'if I recall correctly'
Damn that looks so good. Also thanks for the tip about SnapTo
@tropic inlet what the code actually does
hello, it's me again!, i need help with a problem, the problem is the next;
https://hatebin.com/heyqkvesfa (code to spawn enemies)
with this code i want to make a enemy spawn in a random location between X number and X number in coordinates, i made that with Random.Range, first i only had one place of enemy spawning, the superior part of the map, now i want the code to decide first in wich place it will spawn an enemy (between x and x coordinates of left, right or up), then decide wich enemy and then spawn it only when timeBtwEnemy is zero, the problem is that when i hit play it just instantiate the enemy00 GameObject each frame in 0 0 coordinates and dont spawn other enemies and dont respect the timeBtwEnemy and idk why this happen so if someone can help me or at least told me what is wrong here
(when i say x and x on the explanation im just refering to "a number" not the int called "x")
I haven't looked too closely at your code but I see one obvious problem. Your if statements aren't going to work the way that you wrote them.
uh?
The && operator has higher precedence than the || operator so when you say if(x == 0 || x == 1 && y == 0) you are really saying if(x == 0 || (x == 1 && y == 0))
the problem persists
if(y == 0 && (x == 0 || x == 1)) i basically just changed to this
That look correct. I assume you changed all of the other if statements. You might post the latest revision.
yes, i did it and i posted it
Are you sure that link is for you latest changes?
this one have the new changes
did you found a way to fix it? ๐ง
screenshot of what is happening
another screenshot of the editor
I do see another problem. The big chain of if/else if statements that follow the if (timeBtwEnemy <= 0 && alive) statement look like they should be placed in that block instead of outside of it.
If that makes sense. I'll post the changes here in a second.
no, i think that should break the stuff
if i change first if of the else if chain to an else if it will not execute when is called
Here's what I'm talking about... https://hatebin.com/ttdktvkynu
I reformatted your code so I could make more sense of it.
wait, you can put an if inside another if!?
You only want to spawn a new enemy when (timeBtwEnemy <= 0 && alive) so the code to do that should be in that block.
Hi everyone, does anyone know why I am not getting an "in between value" when im using my controller?```css
private void handleMovement()
{
if (!isUsingController)
{
direction = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
}
else
{
direction = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
print(direction);
}
direction.Normalize();
rb.AddForce(direction * speed, ForceMode2D.Impulse);
//Debug.DrawRay(rb.position, new Vector3(direction.x, direction.y, 0f) * 500f);
}```well.. im getting "the in between" when I print it but when I apply the force its either all or nothing
true
Yeah, it gets really messy so at some point you might think about breaking things into different functions. I would get it working before doing that, however.
Because you are normalizing the direction vector
MAN
it works
thank you so much
i did'nt think the problem was so stupid
LMAO
goodbye
Cool. Have fun!
Also you're printing before the normalize, so that explains why it prints fine
now i know you can put an if iside another if
that will make things a lot easier
tysm
Why do I feel like he's going to use that knowledge for evil and not good?
And watch out when mixing && and || in an if statement. Most people always use parenthesis so that it is explicit how the compiler will evaluate the statement.
ok
@snow willow ohh I see.. Im normalizing this vector because I dont want my player to go faster in some directions. If I remove that line, my controller will work fine but my player will go faster in diagonal.. Is their a way I can make my controller return "inBetween values" while not being able to go faster in corners?
ohhh nice I think this is exactly what I was looking for ๐ thanks man
np
That's the old GoldenEye 007 problem ๐
used to run around diagonally all over the place
lmao yeah
playerCam.orthographicSize = Mathf.Lerp(6f, 9f, 3f);
any idea on why its poping to 9 instead of lerping?
I think the 3rd parameter should have a value between 0 and 1.
You need to call Lerp in steps using Update() or something similar and vary the t parameter from 0 to 1.
If that makes any sense. There are also 3rd party assets that will do that for you such as DOTween.
Sure.
Im having this stupid bug, when i walk I have random yellow lines show up? Anyone know what is going wrong??
hello i have another issue with my unity game
i just deleted a completly diffrent scene, and suddenly my player sprite dissapears when the game "plays" in the editor
now im getting a werid issue about im trying to access a transform object thats deleted
i checked my code and objects and everything is stil connected
Make sure the sprites that you are using for tiles have an Extrude Edges setting of at least 1.
I just check all my sprites. looks like they already had extrude edges at 1
*checked
Are you using a TileMap or did you place the tiles manually?
TileMap I think
So you have a Grid and Tilemap in you scene?
yep
Hmm. Are you using a Cinemachine camera or the standard camera?
Im pretty sure im using the standard camera, but im not sure
um..
If you didn't change it then, yes, you are likely using the standard camera. The Cinemachine camera is improved and I'm pretty sure the issue you are seeing has been fixed with it.
okay
There might be ways to work around the issue with the old camera.
okay
The Cinemachine camera is really nice. Once you get further along in your game it will provide a lot of feature that you would have to otherwise implement yourself.
ok thanks ๐
hey @tropic charm when you are done may i ask a few questions?
I saw your question @keen solar but I don't really have any suggestions. You might post screenshots of the errors.
Probably want to use Mathf.MoveTowards instead of Lerp.
@keen solar If you click on the Console tab and find that error and double-click it it should pull-up the file where the error occurred.
when i click on it, everything points to the player sprite
however when teh game plays the sprite dissapears
Sounds like you have a script that's destroying the player right at the start of the game
Yeah, tracking that down might be tricky. You should double-check all of the code that deals with the player object.
i dont actully.
this only started happening after i deleted a sub scene that displayed a sign of game over
even when i add a new empty object, it dissapears
Is the sprite being removed or greyed out in the scene view when you run the game?
Just changed to Cinemachine, still having those dumb yellow lines..
removed completly
.. it also shows up on the scene viewer
@mortal nexus Really? Are the sprites the proper size? Does the Pixel Per Unit setting match?
Double-check your grid settings.
Yep. That looks okay.
what do you think the problem is then?
I don't know. It sounds like the classic tilemap 'bleed' problem but I've never seen that when things are setup like you done.
What do your Background TileMap settings look like.
I think this is it
The scaling kind of worries me.
what should I change it to?
Here are the settings from a project I'm looking at.
I'll play around with the x and y scale and see if I can reproduce what you're seeing.
okay
thanks
In a sec I have to go eat dinner so if I dont respond right away, that is why
...
I didn't notice any problems when I messed with the scale or position. You might try setting your transform up like mine and see if it helps.
Okay
@keen solar From the sound of it you might have somehow got the IDE confused.
The Unity editor.
ok.
how do i fix it?
Have your restarted Unity? I would start there.
restarted
still the vanishing player
created new empty sprite, re added all rigid bodys, 2d box collider and scripts and the same thing happens
Are you attaching a script to the sprite?
You might post the code from that script. It must be doing something fishy.
adds / */ *
thats very weird
why would that script fire now when it wasnt before when the defunct scene was there?
I don't know. Maybe it was just a coincidence. Anyway, I think you want to use <= (less than or equal) instead of >= (greater than or equal.)
Sure.
Hi. So I am making a game called adventure 2d and I have the character image but the script does not work and it it wasn't compiled properly. Can anyone help?
solved!
@still tendon Have you got a screenshot of the script?
can i use two box colliders and can I query which one was touched?
I am making a 2d game and I want the player to rotate instead of moving, so that it can only move forward or backward. How do I make it so it would rotate?
thanks
i am making 2d game in unity ,i have problem .problem is i want to when damaged from enemy ,knockback to damage direction
how can i do
can anyone help explain why instance wont move to the position printed?
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using UnityEditor.UI;
using UnityEngine;
public class levelGenerator : MonoBehaviour
{
Object[] enemies;
// Start is called before the first frame update
void Start()
{
enemies = Resources.LoadAll("enemies/");
Debug.Log(enemies[0]);
generate(1);
}
public void generate(int level)
{
for (int i = 0; i < 4; i++)
{
Random.InitState(level + i);
GameObject enemy = enemies[0] as GameObject;
Vector3 screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.safeArea.width, Screen.safeArea.height, Camera.main.transform.position.z));
GameObject current = Instantiate(enemy, this.transform.parent) as GameObject;
Vector3 pos = new Vector3(Random.Range(0, screenBounds.x), Random.Range(0, screenBounds.y), screenBounds.z);
Debug.Log(pos);
current.transform.localPosition = pos;
}
}
void Update()
{
}
}
you're setting localPosition not position
so it will go to that position - but transformed by its parent's transform
@snow willow oops i just switched it to local position when trying everything. it didn't work with regular position either
what's happening instead?
Is it not moving at all?
If it's not moving at all the position maybe is being controlled by a CharacterController or an Animator
I do not understand why it is not recognizing transform
Are you missing a using directive?
using UnityEngine;
as the error suggests
Oh also - it's Transform
not transform
for the type
ok
I've got an issue with the colliders, they're taking a little while to show any effect and I'd rather they happen instantaneously
How can I fix this? :P
why not use OnTriggerEnter2D?
oh wait
no you're right
your problem is that you're reading Input.GetMouseButtonDown() inside OnTriggerStay2D
OnTriggerStay2D is part of the physics update
so it doesn't run every frame
Ahh, should I write it to a variable then?
so sometimes you will miss input
yeah read that in Update
save it in a variable
check that variable instead in your OnTriggerStay
Brill, thanks very much
wow I can't believe I didn't think of this. Everything is working now thank you so much!
can anyone help me with a OnMouseDown problem. ?
in my start i instantiate a few GameObject sprites with a 2D box collider on them. i'm trying to click on them and disable them, but for some reason the OnMouseDown section is not getting exacuted
share code?
Where did you attach the script with the OnMouseDown() method? From the API doc: This event is sent to all scripts of the GameObject with Collider or GUIElement. Scripts of the parent or child objects do not receive this event.
Also I believe you need an EventSystem and a PhysicsRaycaster in the scene for OnMouseDown to work but not 100% confident about that
can you show what other components this object has? (Show its inspector)
You need to properly configure Visual studio using the instructions pinned to #๐ปโcode-beginner
Just from the name of the file it doesn't sound like that method is attached to a game object with a collider.
how does one make bullet hell paterns
ohh lord i'm getting lost in the channels
that can't be the same object because I don't see your script on it
I can make it work by attaching a script that has the OnMouseDown() method in it to the game object that has the collider.
using UnityEngine;
public class MonkeyCollider : MonoBehaviour
{
[SerializeField] private Monkey _monkey;
[SerializeField] private bool _isFront;
void OnMouseDown()
{
Debug.Log("Mouse down!");
}
void OnCollisionEnter2D(Collision2D other)
{
if (_monkey)
{
_monkey.Damaged(_isFront);
Destroy(other.gameObject);
}
}
}
no, the script is on the GameControl. and from the game control i instantiate those sprites from a list 2 manipulate them
You will only get OnMouseDown callbacks on the exact GameObject that the collider is on
but all of the images that are being instantiated has a collider on them ? why when i click on their collider it doesn't give me a call back ?
You need two things on the object to get a callback:
- The collider
- A script with OnMouseDown()
on the same object
you need a script on the object you're instantiating
so then i'll have to also attach the script to them also while instantiating them.
will this also work if i make them a child to the game control ?
You can just attach a script to the prefab
that you are instantiating
or whichever object you're copying
and no it doesn't work on parents or children as mentioned above
ahhh ok , thx
hey i need some help with my game
If i set a object to a child from a other, then i can't set the position
GameObject a = Instantiate(SlotPrefab) as GameObject;
a.transform.parent = this.transform;
a.transform.position = new Vector3(i, 0, 0);
Sure you can, you just did
Not he didn't
hey guys hope every one doing good โค๏ธ
i have a question i have to scripts in my camera one for camera follow player with boundaries and the other one is a camera shake script the problem is idk why the camera shake didnt work when the the camera follow script ๐ any one have an idea ??
Idk if this is the right place to ask but I am having a problem with the Destroying Assets is Not Permitted error
@hearty anvil Are you calling Destroy to an asset reference?
I imagine I am but I'm not trying to
This is the problematic bit of code
Bossenemy is a public GameObject I initiated at the top of this script
Btw pls bear with me if I get some terminology wrong I've recently got back into Unity after a like 6 month break and I'm still a beginner ๐
@hearty anvil Bossenemy likely isn't pointing to an instance in the scene, but the file itself
Hmm that is what I suspected. But do you know how I would go about fixing this?
It feels like I'm missing some sort of basic principle because this is an error I would likely see very often otherwise given it's such a simple thing as destroying an instance
Hard to say. If you dragged prefab to that field, then it will point to that prefab until it's replaced. Generally I don't share prefab fields with instance fields and make it clear when naming the field.
Just need to investigate what is assigned to that field
Replaced you say? How do you replace a prefab with an instance?
And if you can do that can you then replace it with a clone and destroy the clone?
As in assign something to a field
Bossenemy = GameObject.Find..., or Bossenemy = Instantiate...
So shouldn't this have worked, then?
This is in my startup script run right at the start
I don't know how any of this connects to the Bossenemy field
I dragged the prefabs into the GameObject tabs, was I supposed to put something else there?
I'm just trying to find what's causing the problem
Tbh this error in general just confuses me
The script I showed creates an instance of the Bossenemy
Again, I don't see where the Bossenemy is referenced outside of the Destroy statement
Idk, what is it in particular is it you need to see?
Do you have a script named Bossenemy? I don't see how your code would compile otherwise.
What is assigned to Bossenemy, since that is the one pointing to an asset
I don't have a script by that name. Bossenemy is a public GameObject variable in the bossController script which is connected to the object called BossEnemy (with the capital E)
You should post your scripts so that we can see everything in context. Use hatebin if they are longer than a few dozen lines.
Ah okay
Hang on I'll post the Boss script and the bossController 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.
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.
Sorry if I've been difficult so far, most of this is new to me ๐
No problem. My guess is that you dragged a prefab into the Bossenemy property. If so then you can't call Destroy() on a prefab. Drag the instance from the scene into that property instead.
Or, maybe you want to be calling Destroy(this.gameObject) if that script is attached to the enemy boss.
Yeah I have just noticed that the prefab is losing health when it gets shot at but the instance in the game is not losing health
When the instance in the game is the one actually taking hits
It won't let me drag the clone in the scene view onto the Bossenemy property
I don't know why that would happen.
what
You mean why it wouldn't let me?
am I allowed to send photos here? why did my message get deleted
Right.
is it possible to create online strings?
uhh, what i wanted to say is I have a button in my game that makes the player jump, but when I press it there's a slight delay.
That property is a GameObject so it should accept Prefabs or instances of prefabs.
Gahhh I don't understand why this part of all things is so confusing. I got stuck here before. I only want this object to be instantiated and to then be destroyed when it needs to be. Idk why everything seems to be editing the prefab's properties instead of that of the instance
I feel like I'm doing something fundamentally wrong and I haven't noticed yet
I figured you drag prefabs into the GameObject fields and it does the rest
Does the boss enemy start life already instantiated in the scene? (Is it in the Scene hierarchy?) Or do yo instantiate it yourself?
I have a GameManager object that loads up the scene and instantiates every object I need
Should I share the code for that script?
No, that's getting a little too complicated to wade through. Just know that, in this case, what you pass as a parameter to Destroy() has to be what was returned from Instantiate().
Alright
I have this in the script at least
And this to instantiate them
I dragged the prefabs into place here
Also, if the BossController script is attached to the BossEnemy prefab then you should be able to call Destroy(this.GameObject) within that script and its base.
Yeah I changed that but it didn't do anything
Note that bossController inherits from Boss and Boss is the script that has that function that destroys it
Not sure if that changes anything or not
From the sounds of it, if the properties are changing on the prefab during gameplay then you still have other problems.
No, I don't think the inheritance is an issue.
Your code is just mixing use of the prefab and the instance of the prefab from the sounds of it.
Yeah that sounds about right
I didn't even know this was a thing though
Geez that means I have to figure out where I referenced the prefab instead of its instance
Sounds like a lot of work ๐
If the object isn't in the scene, it likely isn't referencing anything but prefabs
Objects already in the scene can reference scene objects
I did instantiate the object though
That doesn't affect those references apart from the stuff you assigned while instantiating
The typical use case is that you use the prefab only to create instances via Instantiate<>() but otherwise only use the instances in the gameplay code.
Also, realize that you can use a prefab to create several instances--it isn't a one-to-one relationship.
So what does this mean currently? Would it be an easy enough fix to change all references to instances rather than the prefab or would I have to start some things over?
Personally, I would start by renaming properties that expect prefabs to have 'Prefab' in the name. It looks like you are using 'inst' for instances so that's good.
Then I'd find all the reference and switch to using the instance.
So if I do this for every script I should be fine?
Hard to say but that is where I'd start. You might go line-by-line so that you catch any compiler errors early. And fix them before moving on.
Alright, sounds good
Just don't forget to leave the use of the Prefab in the call to Instantiate(). I'm betting all the other uses can be changed to use the instance.
https://pastebin.com/cjbAXwWV
So I am a bit unsure how I would go about sorting this one, as one of the more important places where this would need to be done
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I guess I don't know precisely how to reference an instance of another object in here instead as a GameObject
Yeah, that's something you won't know at design time since you are creating everything dynamically. That property shouldn't be assigned in the inspector but at runtime.
You might have to use something like FindObjectOfType().
Ideally, you would have the object that is creating the instances pass this information to everyone that needs it.
GameObject.FindWithTag() will work too if you assign a tag to the game object in question.
I'm getting a Object Reference Not Set to Instance of Object error now
I changed bossEnemy to instBossEnemy and added this line of code
The highlighted line here in the inherited script is raising the aforementioned error
Is the class in the second screenshot derived from the first? Maybe you need to call base.Start()?
You might put Debug.Log() calls in those Start() methods to 1) see which order they are called in, and, 2) see if instBossEnemy is actually getting assigned a non-null value.
Found this: https://answers.unity.com/questions/147276/why-is-start-from-my-base-class-ignored-in-my-sub.html
Yeah the 2nd screenshot was being called first
That link shows a couple of way to call base.Start().
Alright! It's responding as it should be now, but it isn't being destroyed when its health goes down to 0
And the prefab is not responding, as it should be
Woohoo! Almost there.
Alright so how should I destroy the object?
Just go with GameObject.Destroy(instBossEnemy)?
Yes, if you have the instance handy then that should work.
Ah I see my mistake, I had to move instBossEnemy in another place as well
Okay so when it dies it's respawning in the middle constantly, but I know what's causing that
...fix one thing and something else pops up. That's the nature of software development.
Alright I've got it!
I now have a tracker for if the boss has or has not been beaten yet which decides whether one should spawn or not
Everything works! :D
Awesome!
Thanks so much guys, this really helped!
Still, I'm surprised this error isn't more common. I got this following the orders of some instructions from an old uni tutorial ๐
Well, you'll know better now if you ever come across the same thing. Good luck with your game development journey.
You too on your own journey 
if I want to make a list with LayerMask, of layers that an object can collide with
how do I write an if statement for that?
what I'm trying to write is, if an object's layer is part of the LayerMask list, then the collision occurs
I have tried having this variable, which gives me a list in the Inspector
and later:
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.layer == WhatCanCollide)
but this isn't working
@terse cloak I don't see any good examples in Unity's documentation that would show how to do this but LayerMask.Value returns a 32-bit value that has all of the layers bitwise-ORed together.
So in your case you should be able to say something like this:
if (other.gameObject.layer.value & WhatCanCollide.value) { ... }
I'll give it a try thanks
Looks like you'll want to say this so the compiler doesn't complain: if ((other.gameObject.layer.value & WhatCanCollide.value) != 0) { ... }
So I have a small little problem, whenever I use MovePosition in my code, the gravity affect on the entity becomes significantly lower and velocity value is constantly 0.
My question is, why do both of these things happen?
Question: I have an object with a collider and a Vector2 that stores the direction the object is facing (which can change at runtime). When a bullet collides with the object I want to check what angle the collision happened relative to the Vector2 facing, so that I can determine whether the bullet hit the object in the front half or the back half of the object. Vector2.Angle seemed like a good idea but it's giving me weird results I don't understand -- how can I do this?
@native thistle Have you tried Vector2.SignedAngle()? Vector2.Angle() will always give a positive result <= 180 degrees.
Both Vector2.Angle and Vector2.SignedAngle seem to give me weird/incorrect results, yeah.
My current implementation is basically:
return DamageAngle.Back;
else
return DamageAngle.Front;```
Is the bullet rotating? Also, I don't think you should need to subtract the object position from the bullet position. The second parameter should probably just be bullet.transform.position.
float angle = Vector3.Angle(_facingVector, projectileVector);
Debug.Log("this._facingVector = " + _facingVector + " projectileVector = " + projectileVector +
" angle = " + angle);
That code there will return a value of 0 when the target is hit in the back and a value of 180 when hit in the front.
The projectile rotates so I had to save off its initial direction and use that as projectileVector.
Hi i am wondering what code do i require if i want to zoom the camera out on collision with a object.
Is your camera using orthographic projection?
Basically, you will just have to animate the camera's Size property.
how do i do that, i am a novice at coding lol
Easiest way to do it would be to create an animation on your camera. Select your camera in the Scene Hierarchy, open the animation window and click 'Create'.
...add orthographic size as a property then change the values in the timeline to your liking.
That's probably not the best way but it is the easiest. Assuming you're familiar with how animating works.
yep
but i wanna learn coding and the best to do that is by asking so how would i approach it if i want to code it ?
To code it, you'll want to change that same parameter (the camera's size) programmatically in Update().
Personally, I would probably use a 3rd party asset like DOTween.
If you don't care about non-linear easing then you can easily use Mathf.Lerp() in Update() to get what you want.
i pm you how would i improve that code? @tropic charm
The bullet always faces its direction of travel, but some bullets seek their targets so those ones rotate during their trajectory, yeah.
Could you elaborate a bit more on what you mean by "The projectile rotates so I had to save off its initial direction and use that as projectileVector."? I feel like I'm missing something from your code snippet. ๐ Either that or for whatever reason I just don't see the whole code.
Let me gather up some code to show you what I was playing with...
First, here's the projectile (a banana, quite deadly.)
using UnityEngine;
public class Banana : MonoBehaviour
{
[SerializeField] public Vector3 throwVector;
void Update()
{
transform.Rotate(new Vector3(0f, 0f, 180.0f * Time.deltaTime), Space.Self);
transform.Translate(throwVector * Time.deltaTime, Space.World);
}
}
Note the throwVector field, which I assign when a projectile is created and thrown. (Not sure why I serialized it.)
void Update()
{
bool fromTheLeft = Input.GetKeyDown(KeyCode.L);
bool fromTheRight = Input.GetKeyDown(KeyCode.R);
if (fromTheLeft || fromTheRight)
{
GameObject projectile = createProjectile(fromTheLeft);
Destroy(projectile, 3.0f); // 3 seconds maximum lifetime.
if (projectile.TryGetComponent<Banana>(out Banana banana))
{
banana.throwVector = fromTheLeft
? new Vector3(20f, 0f, 0f)
: new Vector3(-20f, 0f, 0f);
}
}
}
So, in this case the projectile come strait from the left or right of the target. I'm scaling the vector to affect the speed.
The collider is currently a child of the `target' and is currently doing this... (Which is half-baked.)
using UnityEngine;
public class MonkeyCollider : MonoBehaviour
{
[SerializeField] private Monkey _monkey;
[SerializeField] private bool _isFront;
void OnCollisionEnter2D(Collision2D other)
{
if (other.transform.tag == "Platform")
{
return;
}
Banana banana = other.gameObject.GetComponent<Banana>();
if (_monkey && banana)
{
_monkey.Damaged(_isFront, banana.throwVector);
Destroy(other.gameObject);
}
}
}
Note that it passes the projectile's throwVector.
Finally, Monkey.Damaged() does this...
public void Damaged(bool isFront, Vector3 projectileVector)
{
Vector2 force = isFront
? _KnockbackForce * _frontHitKnockbackVector
: _KnockbackForce * _rearHitKnockbackVector;
_rb2d.AddForce(force);
StartCoroutine(ShowDamage(isFront, projectileVector));
StartCameraZoomAnimation();
}
private IEnumerator ShowDamage(bool isFront, Vector3 projectileVector)
{
// float angle = Vector3.SignedAngle(_facingVector, projectileVector, Vector3.back);
float angle = Vector3.Angle(_facingVector, projectileVector);
Debug.Log("this._facingVector = " + _facingVector + " projectileVector = " + projectileVector +
" angle = " + angle);
_spriteRenderer.sprite = isFront ? _thrownBackSprite : _thrownForwardSprite;
for (int i = 0; i < 2; ++i)
{
_spriteRenderer.material = _hitMaterial;
yield return new WaitForSeconds(0.1f);
_spriteRenderer.material = _originalMaterial;
yield return new WaitForSeconds(0.1f);
}
yield return new WaitForSeconds(0.1f);
_spriteRenderer.sprite = _normalSprite;
}
...which isn't actually using the projectileVector but could.
It doesn't use it because there are actually two colliders on the target. One on the left side and another on the right.